React 组件复用之高阶组件

1、创建高阶组件,代码如下:

import React from 'react'

function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

// 高阶组件
function WithHoc(WrappedComponent) {
    class Hoc extends React.Component {
        state = {
            x: 0,
            y: 0
        }
    
        moveMouse = e => {
            this.setState({
                x: e.clientX,
                y: e.clientY
            })
        }

        componentDidMount() {
            window.addEventListener('mousemove', this.moveMouse)
        }

        componentWillUnmount() {
            window.removeEventListener('mousemove', this.moveMouse)
        }

        render() {
            return <WrappedComponent {...this.state} {...this.props} />
        }
    }

    Hoc.displayName = `WithHoc${getDisplayName(WrappedComponent)}`

    return Hoc
}

export default WithHoc

2、组件运用

import React from 'react'
import WithHoc from './components/move-mouse/WithHoc'

function Mouse(props) {
    return <p>鼠标当前坐标:{props.x},{props.y}</p>
}

const CoordMouse = WithHoc(Mouse)

function App() {
    return (
        <div className="App">
            <CoordMouse />
        </div>
    )
}

export default App

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容