簡體   English   中英

類型“{}”不可分配給類型“IntrinsicAttributes &amp; IntrinsicClassAttributes”<Search> &amp; Readonly&lt;{ children?: ReactNode; }&gt;

[英]Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Search> & Readonly<{ children?: ReactNode; }>

我對 React 和 TypeScript 很陌生。 我正在 Visual Studio 2017 中開發一個網頁,其中有一個我想在我的主頁組件中使用的搜索組件。 但是在將搜索導入我的主組件后,我收到一個編譯時錯誤,說:

Type {} is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Search> & Readonly<{ children?: ReactNode; }>  
Type {} is not assignable to type Readonly<SearchForm>  
 Property 'suggestionList' is missing in type {}

搜索組件代碼:

export class Search extends React.Component<SearchForm> { //SearchForm is a class with string and an object of another class as properties
constructor() {
    super();
}

主頁組件代碼:

   export class Home extends React.Component<RouteComponentProps<{}>, {}> 
   {
   return <div>
        < Search /> // <=Getting error at this line
   <div>
   }

如果我從 Home 組件中刪除RouteComponentProps<{}> ,我會在 route.tsx 文件中收到錯誤消息。 我知道,我一定是做錯了什么或犯了一些愚蠢的錯誤。 我用谷歌搜索了這個,但我沒有得到任何有用的答案。 有人可以告訴我如何解決這個問題嗎?

您缺少Search組件的必需屬性,錯誤顯示suggestion List 你需要這樣的東西:

<div>
  <Search suggestionList={...} />
</div>

(也許不僅僅是suggestionList丟失)

React.Component 定義是:

interface Component<P = {}, S = {}>

其中P定義組件屬性, S定義狀態。 您必須將P定義的所有必需屬性傳遞給組件。

在您的示例中,組件屬性類型是SearchForm 因此,您至少需要傳遞SearchForm所有必需屬性。

請參閱定義道具和狀態類型以獲得更完整的解釋。

正如@Tobías 所說,您缺少 Search 組件所需的屬性。

給所有道具一個值將修復它:

<Search prop1={'string'} prop2={obj} />

如果您想創建功能組件,您可以使用泛型來消除此錯誤。 考慮這個例子。

interface SearchProps {
  suggestionList: any
}

export const Search: React.FC<SearchProps> = ({suggestionList}): JSX.Element => {
   return <div>...</div>
}

你必須傳播道具對象。 詳細說明:

我有這個組件

const Component: FunctionComponent<ComponentProps> =
    (props) => {
//component code
}

在這里調用它; 我們有 props 對象和組件

  const componentProps: ComponentProps= {
        //properties
title:'title 1',
//etc...
    }
<Component/>

要將 props 對象作為 props 分配給組件,您應該將對象散布在組件中

<Component {...componentProps} />

暫無
暫無

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

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