- 父传子:直接通过prop子组件标签身上绑定父组件中的数据即可
- 子传父:在子组件标签身上绑定父组件中的函数,子组件中调用这个函数传递参数
- 总结:思想保持一致;类组件依赖于this
import { Component } from 'react';
class Son extends Component{
// 子组件
render(){
return <div>Son =》 {this.props.msg}<button onClick={() => this.props.onGetSonMsg('son消息')}>传参给父组件</button></div>
}
}
// 父组件
class Parent extends Component{
state = {
msg: 'parent消息',
sonMsg: ''
}
getSonMsg = (sonMsg) => {
console.log(sonMsg)
this.setState({
sonMsg
})
}
render(){
return <div>Parent =》{this.state.sonMsg} <Son msg={this.state.msg} onGetSonMsg={this.getSonMsg} /></div>
}
}
const App = () => {
return (
<div className="home">
<Parent />
</div>
)
}
export default App
