React没有vue那样通过emit发送事件到父组件,只能调用父元素的函数从而操作父元素
还是通过一个案例来具体说明
首先还是先创建一个子组件
class ChildCom extends React.Component{
constructor(props){
super(props)
this.state = {
msg:'hello'
}
}
render(){
return(
<div>
<button onClick={this.sendData}>传递给父</button>
<button onClick={()=>{this.props.setChildData("直接调用props")}}>传递给父</button>
{/* 让我们不用写这个sendData,这个可以代替下面定义的sendData方法 */}
</div>
)
}
sendData=()=>{
console.log(this.state.msg)
//将子元素传递给父元素,实际就是调用父元素传递进来的函数
this.props.setChildData(this.state.msg)
}
}
然后创建父组件
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}></ChildCom>
</div>
)
}
setChildData=(data)=>{
this.setState({
childData:data
})
}
}
比vue是繁琐了一点…通过调用父元素的函数从而操作父元素