父组件向子组件传值,父组件通过初始state,子组件通过this.props进行接收就可以了
子组件向父组件传值,需要绑定一个事件,然后事件是父组件传递过来的this.props.event进行值的更替
父组件向子组件传值
父组件:Parent.js
class Parent extends React.Component {
{/* 省略其他与该知识点无关的代码 */}
constructor(props){
super(props)
this.state = {
parenttochild : false
}
}
render() {
return (
<div>
<Child parenttochild = {this.state.parenttochild } />
</div>
)
}
}
子组件:Child.js
class Child extends React.Component {
{/* 省略其他与该知识点无关的代码 */}
render(){
return (
<div>
{this.props.parenttochild }
</div>
)
}
}
子组件向父组件传值
子组件:Child.js
class Child extends React.Component {
{/* 省略其他与该知识点无关的代码 */}
render(){
const bindChild = item =>{
this.props.bindTest(item)
}
return (
<div>
<span onClick={bindChild.bind(this,true)} />
</div>
)
}
}
父组件:Parent.js
class Parent extends React.Component {
{/* 省略其他与该知识点无关的代码 */}
constructor(props){
super(props)
this.state = {
parenttochild : false
}
}
bindTest(data){
this.setState({
parenttochild :data
});
}
render() {
return (
<div>
<Child bindTest = {data =>this.bindTest(data)} />
</div>
)
}
}