父组件传子: props
class Son extends Component{
render(){
return (
<div>
<h1>{ this.props.msgOfDad }</h1>
</div>
)
}
}
class Dad extends Component{
render(){
let data = 'i am a message from dad'
return (
<Son msgOfDad={ data } />
)
}
}
ReactDOM.render(
<App/>
document.querySelector("#app')
)
子传父:使用回调函数
class Son extends Component{
render(){
return (
//通过 this.props将父组件的绑定在子组件上
<input type="text" onChange={ (e) => this.props.handleChange(e.target.value) }
)
}
}
class Dad extends Component{
constructor(props) {
super(props)
this.state = {
data: ''
}
}
//子组件触发事件将调用该函数
handleChange = text => {
this.setState({
data: text
})
}
render(){
return (
<div>
<p>This message is from Child: { this.state.data }</p>
<Son handleChange = { this.handleChange } />
</div>
)
}
}
ReactDOM.render(
<App/>
document.querySelector("#app')
)
网友评论