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

2 years ago
  1. import React from 'react'
  2. // App 为父组件,SonA、SonB为子组件
  3. // 目标:B组件中的数据传给 SonA
  4. /*
  5. 1.先把 SonB 中的数据通过子传父 传给 App
  6. 2.再把 App 接收到 Son 中的数据通过父传子传给 SonA */
  7. function SonA(props) {
  8. return <div>this is SonA{props.sendAMsg}</div>
  9. }
  10. function SonB(props) {
  11. const bMsg = '来自于B组件中的数据'
  12. return (
  13. <div>
  14. this is SonB<button onClick={() => props.getBMsg(bMsg)}>发送数据</button>
  15. </div>
  16. )
  17. }
  18. class App extends React.Component {
  19. state = {
  20. sendAMsg: '测试父传子',
  21. }
  22. // 声明一个传给 SonB 组件的方法
  23. getBMsg = (msg) => {
  24. console.log(msg)
  25. // 把 msg 数据交给 sendAMsg
  26. this.setState({
  27. sendAMsg: msg,
  28. })
  29. }
  30. render() {
  31. return (
  32. <div>
  33. <SonA sendAMsg={this.state.sendAMsg} />
  34. <SonB getBMsg={this.getBMsg} />
  35. </div>
  36. )
  37. }
  38. }
  39. export default App