简体   繁体   English

React.memo JSX.Element 类型

[英]React.memo JSX.Element types

If you have these simple components:如果你有这些简单的组件:


const Simple = (_props) => {
    return <div>Hello</div>;
}

const SimpleMemo = React.memo(Simple);
const SimpleMemo2 = React.memo((_props): JSX.Element => {
    return <div>Hello</div>;
});

Then SimpleMemo and SimpleMemo2 are inferred to be of different types.那么SimpleMemoSimpleMemo2被推断为不同的类型。 SimpleMemo is React.MemoExoticComponent<(_props: any) => JSX.Element> and SimpleMemo2 is React.NamedExoticComponent<object> . SimpleMemoReact.MemoExoticComponent<(_props: any) => JSX.Element>SimpleMemo2React.NamedExoticComponent<object>

Furthermore, you can't set some properties for SimpleMemo2 even though the code is the same:此外,即使代码相同,您也无法为SimpleMemo2设置一些属性:

    render() {
        return (
            <div>
                <Simple style={{backgroundColor: "green"}}/>
                <SimpleMemo style={{backgroundColor: "green"}}/>
                <SimpleMemo2 style={{backgroundColor: "green"}}/>
            </div>
        );
    }

This gives an error for <SimpleMemo2 style= :这给<SimpleMemo2 style=一个错误:

Type '{ style: { backgroundColor: string; }; }' is not assignable to type 'IntrinsicAttributes & object'.
  Property 'style' does not exist on type 'IntrinsicAttributes & object'.

However it works fine for SimpleMemo .但是它适用于SimpleMemo What is going on here?这里发生了什么? What's the difference between MemoExoticComponent and NamedExoticComponent and how can I make SimpleMemo2 work without having to assign the function to a variable? MemoExoticComponentNamedExoticComponent之间有什么区别?如何使SimpleMemo2工作而不必将 function 分配给变量?

Your props are not typed.你的道具没有打字。 So SimpleMemo "works" but it really just accepts any prop.所以SimpleMemo “有效”,但它实际上只接受任何道具。 For example this works fine, but really shouldn't:例如,这可以正常工作,但实际上不应该:

<SimpleMemo thisDoesNotExist="butNoError" />

SimpleMemo2 on the other hand works as expected - it's giving you an error because you're trying to pass a prop which the component is not expecting.另一方面, SimpleMemo2按预期工作 - 它给你一个错误,因为你试图传递组件不期望的道具。 To fix it, add all the props to the type:要修复它,请将所有道具添加到类型:

type Props = {
  style?: React.CSSProperties;
};

const SimpleMemo2 = React.memo(({ style }: Props): JSX.Element => {
    return <div style={style}>Hello</div>;
});

Now you can use it without issues.现在您可以毫无问题地使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM