【发布时间】:2020-06-11 17:39:33
【问题描述】:
我正在设计一个模态系统,其中模态可以显示在抽屉上(对于小屏幕)或作为模态窗口。
我创建了一个 Wrapper 组件,它使用其中任何一个组件来包装其子组件,具体取决于屏幕大小:
const Wrapper: React.FunctionComponent<any> = ({ children, ...props }) => {
let WrapperComponent: React.FunctionComponent
const modalType = useModalType()
if (modalType === "drawer") {
WrapperComponent = MobileDrawer
} else {
WrapperComponent = ModalContainer
}
return <WrapperComponent {...props}>{children}</WrapperComponent>
}
当我更改窗口大小时,useModalType 会发生变化,Wrapper 会按照预期使用正确的包装器重新呈现。但是子组件被完全重新渲染,失去了自己的状态。
有什么方法可以记住子组件,以便在包装组件更改时保持不变?
【问题讨论】:
-
你看过
shouldComponentUpdate()吗?您可以在子组件中使用它来防止它们重新渲染。 -
我不想在这里使用基于类的组件,所以解决方案可能涉及
useMemo钩子,但我不确定如何...... -
我猜this 是你要找的。span>
-
我能看到
useModalType的代码吗? -
可以分享道具吗?
标签: javascript reactjs react-hooks