react 之props传值

props 可以把数据从父传给子,如果想要实现子传给父数据,可以把数据当成函数的参数传递给父组件,下面给一行代码揣摩:

class ParentCom extends React.Component{

constructor(props){

super(props)

this.state = {

childData:null

}

}

render(){

return (

<div>

<h1>子元素传递过来的数据:{this.state.childData}</h1>

<ChildCom setChildData={this.setChildData}/>

</div>

)

}

setChildData = (data) => {

this.setState({

childData:data

})

}

}

class ChildCom extends React.Component{

constructor(props){

super(props)

this.state = {

msg: "helloworld"

}

}

render(){

return (

<div>

<button onClick={this.sendData}>传递helloword给父元素</button>

</div>

)

}

sendData = () => {

this.props.setChildData(this.state.msg)

}

}

ReactDOM.render(

<ParentCom/>,

document.getElementById('root')

)