【发布时间】:2020-08-20 17:46:22
【问题描述】:
我的包装组件有这个签名
const withReplacement = <P extends object>(Component: React.ComponentType<P>) =>
(props: P & WithReplacementProps) => {...}
顺便说一句,完整的例子在这里https://codepen.io/xitroff/pen/BaKQNed
它从参数组件的道具中获取原始内容
interface WithReplacementProps {
getContent(): string;
}
然后在按钮点击时调用setContent函数。
const { getContent, ...rest } = props;
const [ content, setContent ] = useState(getContent());
我希望所有内容都会被替换(下面的第 1 和第 2 部分)。 这是渲染函数的一部分
return (
<>
<div>
<h4>content from child</h4>
<Component
content={content}
ReplaceButton={ReplaceButton}
{...rest as P}
/>
<hr/>
</div>
<div>
<h4>content from wrapper</h4>
<Hello
content={content}
ReplaceButton={ReplaceButton}
/>
<hr/>
</div>
</>
);
Hello 组件很简单
<div>
<p>{content}</p>
<div>
{ReplaceButton}
</div>
</div>
这就是包装的方式
const HelloWithReplacement = withReplacement(Hello);
但问题是内容仅在第二部分被替换。第一个保持不变。
在主 App 组件中,我也在加载 20 秒后替换内容。
const [ content, setContent ] = useState( 'original content');
useEffect(() => {
setTimeout(() => {
setContent('...too late! replaced from main component');
}, 10000);
}, []);
...当我像这样调用我的包装组件时
return (
<div className="App">
<HelloWithReplacement
content={content}
getContent={() => content}
/>
</div>
);
它也有问题 - 第一部分正在更新,第二部分没有。
【问题讨论】:
标签: reactjs react-hooks higher-order-functions higher-order-components