解決React報(bào)錯(cuò)Functions are not valid as a React child
總覽
產(chǎn)生"Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render."錯(cuò)誤
通常是因?yàn)橐韵聝蓚€(gè)原因:
- 從
render中返回一個(gè)函數(shù)引用而不是一個(gè)組件。 - 使用 react router 路由作為
<Route path="/about" element={About} />,而不是<Route path="/about" element={<About />} />。

這里有個(gè)例子來展示錯(cuò)誤是如何發(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函數(shù),而不是返回真正的JSX元素。
調(diào)用函數(shù)
為了解決這種情況下的錯(cuò)誤,我們可以調(diào)用該函數(shù)。
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;
通過調(diào)用getButton函數(shù),我們返回了button元素從而解決了該錯(cuò)誤。
如果你正在嘗試渲染一個(gè)真正的組件,確保將其用作<Component />而不是Component。
const App = () => {
const Button = () => {
return <button>Click</button>;
};
// ? Using component as <Button />, not Button
return (
<div>
<Button />
</div>
);
};
export default App;
另一個(gè)導(dǎo)致該錯(cuò)誤的原因是,當(dāng)我們?yōu)閞eact router 路由傳遞一個(gè)元素時(shí),比如<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 />} />。
當(dāng)使用react router時(shí),請確保將應(yīng)該為特定路由渲染的組件作為<Component />,而不是Component。
總結(jié)
可以通過以下兩種方式解決錯(cuò)誤:
- 從
render中返回組件而不是函數(shù)。 - 傳遞給路由中
element屬性的是<Component />,而不是Component。
原文鏈接:bobbyhadz.com/blog/react-…
以上就是解決React報(bào)錯(cuò)Functions are not valid as a React child的詳細(xì)內(nèi)容,更多關(guān)于React 報(bào)錯(cuò)Functions valid的資料請關(guān)注腳本之家其它相關(guān)文章!
- 解決React報(bào)錯(cuò)No duplicate props allowed
- 解決React報(bào)錯(cuò)`value` prop on `input` should not be null
- react component changing uncontrolled input報(bào)錯(cuò)解決
- 解決React報(bào)錯(cuò)useNavigate()?may?be?used?only?in?context?of?Router
- 解決React報(bào)錯(cuò)Style prop value must be an object
- 解決React報(bào)錯(cuò)The?tag?is?unrecognized?in?this?browser
- 解決React報(bào)錯(cuò)Cannot assign to 'current' because it is a read-only property
- Objects are not valid as a React child報(bào)錯(cuò)解決
相關(guān)文章
React團(tuán)隊(duì)測試并發(fā)特性詳解
這篇文章主要為大家介紹了React團(tuán)隊(duì)測試并發(fā)特性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08

