高阶组件不是一种功能,而是一种模式

    1. // 高阶组件 基本用法
    2. const HOCFactory = (Component) => {
    3. class HOC extends React.Component {
    4. // 在此定义多个组件的公共逻辑
    5. render () {
    6. return <Component {...thi.props} /> // 返回拼装的结果
    7. }
    8. }
    9. return HOC
    10. }
    11. const MyComponent1 = HOCFactory(WrappedComponent1)
    12. const MyComponent2 = HOCFactory(WrappedComponent2)
    1. import React from 'react'
    2. // 高阶组件
    3. const withMouse = (Component) => {
    4. class withMouseComponent extends React.Component {
    5. constructor(props) {
    6. super(props)
    7. this.state = { x: 0, y: 0 }
    8. }
    9. handleMouseMove = (event) => {
    10. this.setState({
    11. x: event.clientX,
    12. y: event.clientY
    13. })
    14. }
    15. render() {
    16. return (
    17. <div style={{ height: '500px' }} onMouseMove={this.handleMouseMove}>
    18. {/* 1. 透传所有 props 2. 增加 mouse 属性 */}
    19. <Component {...this.props} mouse={this.state}/>
    20. </div>
    21. )
    22. }
    23. }
    24. return withMouseComponent
    25. }
    26. const App = (props) => {
    27. const a = props.a
    28. const { x, y } = props.mouse // 接收 mouse 属性
    29. return (
    30. <div style={{ height: '500px' }}>
    31. <h1>The mouse position is ({x}, {y})</h1>
    32. <p>{a}</p>
    33. </div>
    34. )
    35. }
    36. export default withMouse(App) // 返回高阶函数