版权声明:前端菜鸟--人间草木所有 https://blog.csdn.net/qq_43258252/article/details/87970051
效果图:
子组件
import React, { Component } from 'react'
class myInfo extends Component {
constructor(props) {
super(props)
this.state = {}
}
componentWillMount() {
this.props.toChild('我是react子组件传给父组件的信息');
}
sendMsg = () => {
this.props.toChild('我是点击后react子组件传给父组件的信息');
}
render() {
return (
<div className="myInfo">
myInfo
<br />
<br />
<button onClick={this.sendMsg}>点击传给父组件</button>
</div>
)
}
}
export default myInfo
父组件
import React, { Component } from 'react'
// 引用子组件 声明的名字 必须大写
import MyInfo from './myInfo'
class my extends Component {
constructor(props) {
super(props)
// console.log(props)
this.state = {}
}
fromMeg = (e) => {
// 获取子组件传过来的信息
console.log(e)
}
componentWillMount() {
}
render() {
return (
<div className="my">
my我的
{/* 父组件中 toChild={this.fromMeg.bind(this)} 父组件给子组件传一个函数fromMeg */}
<MyInfo toChild={this.fromMeg.bind(this)} />
</div>
)
}
}
export default my