子父通信(class组件中的子父组件)
顺序的话先写子组件再写父组件
父组件:
import React from "react";
import Child from "./Chid";
import Second from "./Second";
class Parent extends React.Component {
constructor() {
super();
this.state = {
msg: '下午睡觉了 ',
message: '睡醒了',
num:0
}
}
getMessage(val, count) {
console.log('接受子组件的数据集', val, count );
this.setState({
num:count
})
}
render() {
return (
<div>
<p>父组件 --- {this.state.num}</p>
{/* <Child title='自定义的静态数据' msg={this.state.msg} message={this.state.message}></Child> */}
<Second msg={this.state.msg} a={this.getMessage.bind(this)}></Second>
</div>
)
}
}
export default Parent;
子组件:
import React from "react";
class Second extends React.Component {
constructor() {
super();
this.state = {
count: 100
}
}
toParent(){
// console.log(this.props);
// 子父通信: 把自定义事件直接挂载到this.props对象上; this.props.自定义方法名(数据)
this.props.a('success', this.state.count)
}
render() {
return (
<div>
{/* 子组件接收父组件的数据: 直接通过 this.props.xxx */}
<p onClick={this.toParent.bind(this)}>接收父组件传递的数据 ---- {this.props.msg}</p>
</div>
)
}
}
export default Second;

浙公网安备 33010602011771号