如果您有以下这些简单组件:
const Simple = (_props) => {
return <div>Hello</div>;
}
const SimpleMemo = React.memo(Simple);
const SimpleMemo2 = React.memo((_props): JSX.Element => {
return <div>Hello</div>;
});然后推断SimpleMemo和SimpleMemo2属于不同的类型。SimpleMemo是React.MemoExoticComponent<(_props: any) => JSX.Element>,SimpleMemo2是React.NamedExoticComponent<object>。
此外,即使代码是相同的,也不能为SimpleMemo2设置一些属性:
render() {
return (
<div>
<Simple style={{backgroundColor: "green"}}/>
<SimpleMemo style={{backgroundColor: "green"}}/>
<SimpleMemo2 style={{backgroundColor: "green"}}/>
</div>
);
}这给<SimpleMemo2 style=带来了一个错误
Type '{ style: { backgroundColor: string; }; }' is not assignable to type 'IntrinsicAttributes & object'.
Property 'style' does not exist on type 'IntrinsicAttributes & object'.但是,它对SimpleMemo很好。这里发生什么事情?MemoExoticComponent和NamedExoticComponent之间有什么区别,我如何使SimpleMemo2工作,而不必将函数赋值给变量呢?
发布于 2022-09-23 11:10:03
你的道具没有打字。因此,SimpleMemo“工作”,但它真的接受任何道具。例如,这很好,但实际上不应该:
<SimpleMemo thisDoesNotExist="butNoError" />另一方面,SimpleMemo2按预期工作--它给您一个错误,因为您试图传递组件不期望的道具。要修复它,请将所有道具添加到类型中:
type Props = {
style?: React.CSSProperties;
};
const SimpleMemo2 = React.memo(({ style }: Props): JSX.Element => {
return <div style={style}>Hello</div>;
});现在你可以毫无问题地使用它了。
https://stackoverflow.com/questions/73826700
复制相似问题