donaricano-btn

리액트 이벤트와 컴포넌트 데이터 교환


1. 클릭 이벤트 와 상태 저장 컴포넌트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Count extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            counter : 0
        }
    }
    handleClick(event){
        this.setState({counter:++this.state.counter})
    }
    render(){
        return(
            <div>
                <button onClick={this.handleClick.bind(this)} className="btn btn-primary">
                    Don't click me {this.state.counter}
                </button>
            </div>
        )
    }
 
 
}
 
 
ReactDOM.render(
    <Count/>,
    document.getElementById('app')
)

- 이벤트와 상태를 같이 사용함으로 동적인 UI 구성이 가능해진다


2. 클릭 이벤트 와 상태 저장/비저장 컴포넌트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Content extends React.Component{
    constructor(props){
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.state = {
            counter : 0
        }
    }
    handleClick(event){
        this.setState({counter:++this.state.counter})
    }
    render(){
        return(
            <div>
                <DumbCount counter={this.state.counter} handler={this.handleClick}/>
            </div>
        )
    }
 
 
}
 
const DumbCount = (props) => {
    return <button onClick={props.handler} className="btn btn-primary">
        Increase Volume {props.counter}
    </button>
}
 
 
ReactDOM.render(
    <Content/>,
    document.getElementById('app')
)

- DumbCount라는 비저장 컴포넌트를 생성했다.

- 부모 컴포넌트(Content) 에서 자식 컴포넌트(dumbCount)로 이벤트 핸들러를 전송하여 비저장 상태컴포넌트에서 이벤트가 작동하도록 했다


3. 컴포넌트간의 데이터 교환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Content extends React.Component{
    constructor(props){
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.state = {
            counter : 0
        }
    }
    handleClick(event){
        this.setState({counter:++this.state.counter})
    }
    render(){
        return(
            <div>
               <DumbCount handler={this.handleClick}/>
                <br/>
                <Counter value={this.state.counter}/>
            </div>
        )
    }
 
}
 
const Counter = props => <span>Clicked {props.value}</span>
 
const DumbCount = props => <button onClick={props.handler} className="btn btn-primary">Don't do that</button>
 
 
ReactDOM.render(
    <Content/>,
    document.getElementById('app')
)

DumbCount, Counter라는 두개의 비저장 컴포넌트를 만들고 상위로 부모 컴포넌트인  Content 를 두어서 데이터 교환을 한다

- 컴포넌트 간의 강한 결합을 방지하고자 상위 컴포넌트를 매개의 역할 로 사용한다.

- 주로 이벤트 핸들러는 상위컴포넌트에 작성하지만 이벤트가 하나의 자식에게만 영향을 끼친다면 해당 컴포넌트에 작성하도록 한다.  


블로그 이미지

리딩리드

,