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.

40 lines
803 B

2 years ago
  1. import React from 'react'
  2. // APP 为父组件,Son 为子组件
  3. // 父传子:props + 函数
  4. // 子传父:子组件通过父组件传递过来的函数,并且把想要传递的数据当成函数的实参传入即可
  5. function Son(props) {
  6. const { getSonMsg } = props
  7. function clickHandler() {
  8. const sonMsg = '这里是来自子组件中的数据'
  9. getSonMsg(sonMsg)
  10. }
  11. return (
  12. <div>
  13. this is son
  14. <button onClick={clickHandler}>click</button>
  15. </div>
  16. )
  17. }
  18. class App extends React.Component {
  19. state = {
  20. list: [1, 2, 3],
  21. }
  22. // 1.准备一个函数,传给子组件
  23. getSonMsg = (SonMsg) => {
  24. console.log(SonMsg)
  25. }
  26. render() {
  27. return (
  28. <div>
  29. <Son getSonMsg={this.getSonMsg}></Son>
  30. </div>
  31. )
  32. }
  33. }
  34. export default App