为组件设置displayName进行调试工具区别(关键代码)
// 为组件设置displayName,方便调试工具调试
mouse.displayName = `WithMose${getDisplayName(WrappedComponent)}`
function getDisplayName(WrappedComponent) {
// 返回组件的displayName,没有就是组件的name,再没有就是'Component'
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}
高阶组件HOC使用一个函数包裹组件,将逻辑写在函数内部
import React, { Component } from 'react'
//hoc 高阶组件规范,with开头,WrappedComponent组件首字母大写
export function withMouse(WrappedComponent) {
class mouse extends Component {
state = {
x: 0,
y: 0,
}
handleMouseMove = ({ clientX: x, clientY: y }) => {
this.setState({ x, y })
}
componentDidMount() {
window.addEventListener('mousemove', this.handleMouseMove)
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.handleMouseMove)
}
render() {
// 将参数以props传递, {...this.state}高阶组件的state {...this.props}上层的组件props
return <WrappedComponent {...this.state} {...this.props}></WrappedComponent>
}
}
// 为组件设置displayName,方便调试工具调试
mouse.displayName = `WithMose${getDisplayName(WrappedComponent)}`
// 将其返回
return mouse
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}
使用
import { withMouse } from '../hooks/withMouse'
// 传入的参数组件,组件ui
const Position = ({ x, y }) => (
<p>
鼠标当前位置:(x:{x},y:{y})
</p>
)
// 增强组件
const MousePosition = withMouse(Position)
export default class index extends Component {
render() {
return (
<div>
index
<MousePosition />
</div>
)
}
}