React報錯Type '() => JSX.Element[]' is not assignable to type FunctionComponent
總覽
當我們嘗試從函數(shù)組件中返回元素組成的數(shù)組時,會產生"Type '() => JSX.Element[]' is not assignable to type FunctionComponent"錯誤。為了解決該錯誤,可以將元素數(shù)組包裹在React片段中。
這里有個示例用來展示錯誤是如何發(fā)生的。
// App.tsx import React from 'react'; // ?? Type '() => JSX.Element[]' is not assignable to type 'FunctionComponent<{}>'. // Type 'Element[]' is missing the following properties // from type 'ReactElement<any, any>': type, props, key ts(2322) const App: React.FunctionComponent = () => { return ['Alice', 'Bob'].map(element => <div key={element}>{element}</div>); }; export default App;
這是完全有效的React.js代碼,因為我們能夠從React的函數(shù)組件中返回一個數(shù)組。然而,FunctionComponent
接口的返回類型是ReactElement
或null
。
這也就意味著,我們可以只返回一個React元素或者null
值。
React片段
為了解決該類型錯誤,我們必須將數(shù)組包裹在React片段(React fragment)中。
// App.tsx import React from 'react'; const App: React.FunctionComponent = () => { return ( <> {['Alice', 'Bob'].map(element => ( <div key={element}>{element}</div> ))} </> ); }; export default App;
當我們需要對一個元素列表進行分組而不向DOM添加額外的節(jié)點時,就會用到片段。
React.Fragment
你可能還會看到使用了更加詳細的片段語法。
// App.tsx import React from 'react'; const App: React.FunctionComponent = () => { return ( <React.Fragment> {['Alice', 'Bob'].map(element => ( <div key={element}>{element}</div> ))} </React.Fragment> ); }; export default App;
上面的兩個例子達到了相同的結果--它們對元素列表的元素進行分組,而沒有給DOM添加額外的節(jié)點。
div
另一個解決方案是將元素數(shù)組包裹在另一個DOM元素中,例如一個div。
// App.tsx import React from 'react'; const App: React.FunctionComponent = () => { return ( <div> {['Alice', 'Bob'].map(element => ( <div key={element}>{element}</div> ))} </div> ); }; export default App;
這仍然符合FunctionComponent
接口中指定的返回類型,因為我們的組件返回的是一個單一的React元素。
總結
為了解決"Type '() => JSX.Element[]' is not assignable to type FunctionComponent"錯誤,可以使用React片段或者div
將元素數(shù)組進行包裹。
以上就是React報錯Type '() => JSX.Element[]' is not assignable to type FunctionComponent的詳細內容,更多關于React報錯FunctionComponent的資料請關注腳本之家其它相關文章!
相關文章
react實現(xiàn)一個優(yōu)雅的圖片占位模塊組件詳解
這篇文章主要給大家介紹了關于react如何實現(xiàn)一個還算優(yōu)雅的占位模塊圖片組件的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-10-10聊聊ant?design?charts?獲取后端接口數(shù)據展示問題
今天在做項目的時候遇到幾個讓我很頭疼的問題,一個是通過后端接口成功訪問并又返回數(shù)據,但拿不到數(shù)據值。其二是直接修改state中的data,console中數(shù)組發(fā)生變化但任然數(shù)據未顯示,這篇文章主要介紹了ant?design?charts?獲取后端接口數(shù)據展示,需要的朋友可以參考下2022-05-05