解决React报错Functions are not valid as a React child
本文详细解析了React中“Functions are not valid as a React child”报错的原因及解决方案。主要涉及在render方法中错误返回函数引用而非组件实例,以及在React Router中Route组件的element属性使用不当。通过调用函数和使用正确的JSX语法即可修复该问题。
总览
生成“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 />} />使用。

此处提供一段代码示例以演示该错误的触发机制。
// 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;
引发此错误的另一原因是,向 react 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相关信息请参阅本站其他文章!
JS在线运行环境怎么引入Vue、React等第三方库
2026-11-04 23:54:46
dva 中怎么发起异步请求?effects 配合 call/put 实战
2026-11-03 18:25:53
React和Vue中利用JS三元运算符进行条件渲染
2026-11-03 11:20:51
基于原生JS与CSS变量实现可拖拽容器布局组件
2026-10-31 09:34:33
React脚手架config-overrides.js文件的配置方式
2026-10-31 07:13:03







