父组件:
import React, {Component} from 'react';
import Child from "./Child";
class Parent extends Component {
constructor(props) {
super(props);
this.state={
value : ""
}
}
clickHandle=(data)=>{
this.setState({
value : data
})
}
render() {
return (
// onMyEvent方法接收到了来自子组件的参数
// title给子组件传递参数
<div>
{this.state.value}
<Child title="子标题" onMyEvent={this.clickHandle}/>
</div>
);
}
}
export default Parent;
子组件:
import React, {Component} from 'react';
class Child extends Component {
clickHandle = (e) => {
//把子组件的数据通过方法传递给父组件
this.props.onMyEvent("父标题");
}
render() {
return (
//接收到从父组件传进来的参数props.title
<div>
{this.props.title}
<button onClick={this.clickHandle}>数据传递</button>
</div>
);
}
}
export default Child;