리액트 이벤트와 컴포넌트 데이터 교환
1. 클릭 이벤트 와 상태 저장 컴포넌트
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. 클릭 이벤트 와 상태 저장/비저장 컴포넌트
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. 컴포넌트간의 데이터 교환
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 를 두어서 데이터 교환을 한다
- 컴포넌트 간의 강한 결합을 방지하고자 상위 컴포넌트를 매개의 역할 로 사용한다.
- 주로 이벤트 핸들러는 상위컴포넌트에 작성하지만 이벤트가 하나의 자식에게만 영향을 끼친다면 해당 컴포넌트에 작성하도록 한다.
'Front-End > ReactJs' 카테고리의 다른 글
[ReactJs] 리엑트 폼 요소 정의 (0) | 2018.08.07 |
---|---|
[ReactJs] 리액트 폼 이벤트 설정 (0) | 2018.08.05 |
[ReactJs] 리액트 컴포넌트 라이프사이클 (0) | 2018.08.05 |
[ReactJs] 리액트 상태저장 컴포넌트와 상태비저장 컴포넌트 (0) | 2018.08.05 |
[ReactJs] webpack + babel + reactjs 환경셋팅하기 (0) | 2018.07.29 |