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.

67 lines
1.3 KiB

2 years ago
  1. import React from 'react'
  2. // App 为父组件,Son 为子组件
  3. // 函数式的 Son
  4. /* function SonF (props) {
  5. // 解构赋值
  6. // 第一种写法
  7. const { list, userInfo, getMes, child } = props
  8. return (
  9. <div>函数子组件
  10. {list.map(item => <p key={item}> {item} </p>)}
  11. {userInfo.name}{<br />}
  12. <button onClick={getMes}>触发父组件传入的函数</button>{<br />}
  13. {child}
  14. </div>
  15. )
  16. } */
  17. // 解构赋值
  18. // 第二种写法
  19. function SonF({ list, userInfo, getMes, child }) {
  20. return (
  21. <div>
  22. 函数子组件
  23. {list.map((item) => (
  24. <p key={item}> {item} </p>
  25. ))}
  26. {userInfo.name}
  27. {<br />}
  28. <button onClick={getMes}>触发父组件传入的函数</button>
  29. {<br />}
  30. {child}
  31. </div>
  32. )
  33. }
  34. // 类组件的 App
  35. class App extends React.Component {
  36. // 准备数据
  37. state = {
  38. list: [1, 2, 3],
  39. userInfo: {
  40. name: 'Ken',
  41. age: 20,
  42. },
  43. }
  44. getMes = () => {
  45. console.log('父组件中的函数')
  46. }
  47. render() {
  48. return (
  49. <div>
  50. {/* 在子组件身上绑定属性,属性名可以自定义,保持语义化 */}
  51. <SonF
  52. list={this.state.list}
  53. userInfo={this.state.userInfo}
  54. getMes={this.getMes}
  55. child={<span>this is span</span>}
  56. />
  57. </div>
  58. )
  59. }
  60. }
  61. export default App