1.子组件使用this.props.函数名来传值
import React, { Component } from "react";
export default class Son extends Component {
constructor(props) {
super(props);
this.state = {
zitext: "我是子组件的008,我要传递给父组件"
};
}
render() {
return (
<div>
{/* fufun是子组件定义的方法,父组件中要用这个方法来接受数据,this.state.zitext就是数据*/}
<button onClick={this.props.fufun.bind(this, this.state.ziText)}>
点我进行数据的发送
</button>
</div>
);
}
}
2.父组件中要以子组件定义的方法名来定义一个方法,并接受数据
import React, { Component } from "react";
import Son from "./Son";
export default class Father extends Component {
constructor(props) {
super(props);
this.state = {
text: "我是默认值"
};
}
// text就是传递过来的数据
dataFun = text => {
console.log(text);
// 将从子组件取过来的数据设置到当前页面上
this.setState({ text });
};
render() {
return (
<div>
我是父组件father--{this.state.text}
{/*fufun是子组件定义的,fafaun是父组件定义的函数*/}
<Son text="父组件的值001" fufun={this.dataFun} />
</div>
);
}
}