【问题标题】:Very simple MWE, typescript error TS2322 (...) not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'非常简单的 MWE,打字稿错误 TS2322 (...) 不能分配给类型 'IntrinsicAttributes & Props & { children?: ReactNode; }'
【发布时间】:2020-04-09 12:07:37
【问题描述】:

我正在处理一个React/typescript 项目。我试图绕过错误TS2322 并解决它。

Type '{ submissionsArray: SubmissionProps[]; }' is not assignable to type 'IntrinsicAttributes & SubmissionProps[] & { children?: ReactNode; }'.
  Property 'submissionsArray' does not exist on type 'IntrinsicAttributes & SubmissionProps[] & { children?: ReactNode; }'.  TS2322

我看到很多人都遇到了问题,解决方案要么不适用于我的情况,要么就是魔法。

这是非常短的 MWE

import React, { FunctionComponent } from 'react'

type Props = {
    name: string
}

const PropsSpan: FunctionComponent<Props> = (props) => <span>{props.name}</span>

const PropsComponent = () => {
    const p: Props = { name: 'George' }
    return <PropsSpan props={p}></PropsSpan>
}

export default PropsComponent

我尝试过的:一个神奇的解决方案是使用{...p},但我不明白为什么,它还需要在功能组件的末尾附加说明,如果我正在处理一系列道具。

我的问题:如何解决这个错误?

【问题讨论】:

  • 如果你想这样做,你的道具必须看起来像:type Props = {props:{name: string}}

标签: reactjs typescript react-typescript


【解决方案1】:

您没有正确传递道具。道具应该像这样直接作为属性传递给组件:

const PropsComponent = () => {
    return <PropsSpan name="George"></PropsSpan>
}

如果您想先创建 props 对象,然后将其作为 props 传递给 PropsSpan 组件,您可以改用对象解构,如下所示:

const PropsComponent = () => {
    const p: Props = { name: 'George' }
    return <PropsSpan {...p}></PropsSpan>
}

效果和上面一样,虽然不推荐。

【讨论】:

    【解决方案2】:

    你可以用这个,但绝对不是 JSX 方式。

    import React, {ReactElement} from 'react';
    
    interface ComponentProps {
        str: string;
    }
    
    const Component = (props: ComponentProps): ReactElement => {
        return <p>{props.str}</p>;
    };
    
    
    
    const App = (): ReactElement => {
        const props: ComponentProps = {
            str: 'hey',
        };
    
        return (
            <div>
                {React.createElement(Component, props)}
            </div>
        );
    };
    

    我建议使用扩展运算符 ...,就像您在问题中告诉我们的那样,由 Phoenix 提出。

    你说你不会明白所以快速解释一下:

    const obj1 = {a: 'foo', b: 'bar'};
    
    const obj2 = {
        something: 'hello world',
        ...obj1,
    };
    console.log(obj2) -> {a: 'foo', b: 'bar', something: 'hello world'};
    

    Spread Syntax refference

    所以在你的情况下,它会像这样填充道具:

    <Component
        prop1={<something>}
        prop2={<something>}
    />
    

    而你所做的是:

    <Component
       props={{prop1: <something>, props2: <something>}}
    />
    

    该界面必须如下所示:

    interface ComponentProps {
        props: {
            prop1: SomeType;
            prop2: SomeType;
       };
    };
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2018-10-24
      • 2020-08-25
      • 2021-10-29
      • 2022-12-09
      • 2021-10-25
      • 2021-07-12
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多