React组件逻辑复用的三种实现方式对比
HOC
- 组件嵌套过多,不易渲染,不易调试
- HOC会劫持props,必须严格规范,容易出现疏漏
Render Props
- 学习成本高,不易理解
- 只能传递纯函数,默认下纯函数功能有限
Hooks
- 完全符合Hooks的原有规则
- 变量和作用域明确
- 不会产生组件嵌套
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import { useState, useEffect } from 'react'
function useMousePosition() { const [x, setX] = useState(0) const [y, setY] = useState(0)
useEffect(() => { function mouseMoveHandler(event) { setX(event.clientX) setY(event.clientY) } document.body.addEventListener('mousemove', mouseMoveHandler) return () => document.body.removeEventListener('mousemove', mouseMoveHandler) }, [])
return [x, y] }
export default useMousePosition
const [x, y] = useMousePosition()
return ( <div>{x}<div> <div>{y}<div> )
|