解決React報錯Functions are not valid as a React child
總覽
產生"Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render."錯誤
通常是因為以下兩個原因:
- 從
render中返回一個函數引用而不是一個組件。 - 使用 react router 路由作為
<Route path="/about" element={About} />,而不是<Route path="/about" element={<About />} />。

這里有個例子來展示錯誤是如何發(fā)生的。
// App.js
/**
* ?? Functions are not valid as a React child.
* This may happen if you return a Component instead of <Component /> from render.
* Or maybe you meant to call this function rather than return it.
*/
const App = () => {
const getButton = () => {
return <button>Click</button>;
};
// ??? returning function not JSX element from render
return <div>{getButton}</div>;
};
export default App;
上面代碼片段的問題在于,我們從render方法中返回getButton函數,而不是返回真正的JSX元素。
調用函數
為了解決這種情況下的錯誤,我們可以調用該函數。
const App = () => {
const getButton = () => {
return <button>Click</button>;
};
// ? now returning the actual button
// added parenthesis () to call the function
return <div>{getButton()}</div>;
};
export default App;
通過調用getButton函數,我們返回了button元素從而解決了該錯誤。
如果你正在嘗試渲染一個真正的組件,確保將其用作<Component />而不是Component。
const App = () => {
const Button = () => {
return <button>Click</button>;
};
// ? Using component as <Button />, not Button
return (
<div>
<Button />
</div>
);
};
export default App;
另一個導致該錯誤的原因是,當我們?yōu)閞eact router 路由傳遞一個元素時,比如<Route path="/about" element={About} /> 。
// ?? wrong syntax
<Route path="/about" element={About} />
// ? right syntax
<Route path="/about" element={<About />} />
在 react router v6 中,我們不向 Route 組件傳遞 children 屬性,而是使用 element 屬性。例如,<Route path="/about" element={<About />} />。
當使用react router時,請確保將應該為特定路由渲染的組件作為<Component />,而不是Component。
總結
可以通過以下兩種方式解決錯誤:
- 從
render中返回組件而不是函數。 - 傳遞給路由中
element屬性的是<Component />,而不是Component。
原文鏈接:bobbyhadz.com/blog/react-…
以上就是解決React報錯Functions are not valid as a React child的詳細內容,更多關于React 報錯Functions valid的資料請關注腳本之家其它相關文章!
- 解決React報錯No duplicate props allowed
- 解決React報錯`value` prop on `input` should not be null
- react component changing uncontrolled input報錯解決
- 解決React報錯useNavigate()?may?be?used?only?in?context?of?Router
- 解決React報錯Style prop value must be an object
- 解決React報錯The?tag?is?unrecognized?in?this?browser
- 解決React報錯Cannot assign to 'current' because it is a read-only property
- Objects are not valid as a React child報錯解決
相關文章
React前端開發(fā)createElement源碼解讀
這篇文章主要為大家介紹了React前端開發(fā)createElement源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

