1 回答
TA贡献1776条经验 获得超12个赞
HOC 和渲染道具有很多不同的用途,所以我不可能将它们全部都涵盖在内,但基本上该段落指出,您使用 HOC/渲染道具的许多情况也可以通过钩子实现。这不会使 HOCs/render props 过时,但钩子是另一个可供您在组件之间共享代码的工具。
HOC/render prop 的一项常见工作是管理一些数据的生命周期,并将该数据传递给派生组件或子组件。在以下示例中,目标是获取窗口宽度,包括与之相关的状态管理和事件侦听。
HOC 版本:
function withWindowWidth(BaseComponent) {
class DerivedClass extends React.Component {
state = {
windowWidth: window.innerWidth,
}
onResize = () => {
this.setState({
windowWidth: window.innerWidth,
})
}
componentDidMount() {
window.addEventListener('resize', this.onResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize);
}
render() {
return <BaseComponent {...this.props} {...this.state}/>
}
}
// Extra bits like hoisting statics omitted for brevity
return DerivedClass;
}
// To be used like this in some other file:
const MyComponent = (props) => {
return <div>Window width is: {props.windowWidth}</div>
};
export default withWindowWidth(MyComponent);
渲染道具版本:
class WindowWidth extends React.Component {
propTypes = {
children: PropTypes.func.isRequired
}
state = {
windowWidth: window.innerWidth,
}
onResize = () => {
this.setState({
windowWidth: window.innerWidth,
})
}
componentDidMount() {
window.addEventListener('resize', this.onResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.onResize);
}
render() {
return this.props.children(this.state.windowWidth);
}
}
// To be used like this:
const MyComponent = () => {
return (
<WindowWidth>
{width => <div>Window width is: {width}</div>}
</WindowWidth>
)
}
最后但并非最不重要的是,钩子版本
const useWindowWidth = () => {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, [])
return width;
}
// To be used like this:
const MyComponent = () => {
const width = useWindowWidth();
return <div>Window width is: {width}</div>;
}
添加回答
举报