簡體   English   中英

非常簡單的 MWE,typescript 錯誤 TS2322 (...) 不能分配給類型 'IntrinsicAttributes & Props & { children?: ReactNode; }'

[英]Very simple MWE, typescript error TS2322 (…) not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

我正在做一個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},但我不明白為什么,如果我正在使用道具數組,它還需要在功能組件的末尾附加說明。

我的問題:如何解決這個錯誤?

你沒有正確傳遞道具。 道具應該直接作為屬性傳遞給組件,如下所示:

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

如果要先創建道具 object,然后將其作為道具傳遞給PropsSpan組件,則可以改用 object 解構,如下所示:

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

它產生與上述相同的效果,但不建議這樣做。

你可以使用它,但它絕對不是 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'};

擴展語法參考

因此,在您的情況下,它將像以下一樣填充道具:

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

而你所做的是:

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

該界面必須如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM