You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
960 B
45 lines
960 B
import React from 'react'
|
|
// App 为父组件,SonA、SonB为子组件
|
|
|
|
// 目标:B组件中的数据传给 SonA
|
|
/* 方案:
|
|
1.先把 SonB 中的数据通过子传父 传给 App
|
|
2.再把 App 接收到 Son 中的数据通过父传子传给 SonA */
|
|
|
|
function SonA(props) {
|
|
return <div>this is SonA,{props.sendAMsg}</div>
|
|
}
|
|
|
|
function SonB(props) {
|
|
const bMsg = '来自于B组件中的数据'
|
|
return (
|
|
<div>
|
|
this is SonB<button onClick={() => props.getBMsg(bMsg)}>发送数据</button>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
class App extends React.Component {
|
|
state = {
|
|
sendAMsg: '测试父传子',
|
|
}
|
|
// 声明一个传给 SonB 组件的方法
|
|
getBMsg = (msg) => {
|
|
console.log(msg)
|
|
// 把 msg 数据交给 sendAMsg
|
|
this.setState({
|
|
sendAMsg: msg,
|
|
})
|
|
}
|
|
|
|
render() {
|
|
return (
|
|
<div>
|
|
<SonA sendAMsg={this.state.sendAMsg} />
|
|
<SonB getBMsg={this.getBMsg} />
|
|
</div>
|
|
)
|
|
}
|
|
}
|
|
|
|
export default App
|