1 回答

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
HOC 和渲染道具有很多不同的用途,所以我不可能將它們?nèi)慷己w在內(nèi),但基本上該段落指出,您使用 HOC/渲染道具的許多情況也可以通過鉤子實(shí)現(xiàn)。這不會(huì)使 HOCs/render props 過時(shí),但鉤子是另一個(gè)可供您在組件之間共享代碼的工具。
HOC/render prop 的一項(xiàng)常見工作是管理一些數(shù)據(jù)的生命周期,并將該數(shù)據(jù)傳遞給派生組件或子組件。在以下示例中,目標(biāo)是獲取窗口寬度,包括與之相關(guān)的狀態(tài)管理和事件偵聽。
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>;
}
添加回答
舉報(bào)