解决React报错Functions are not valid as a React child

作者:北岛

时间:2026-10-26

浏览:552

本文详细解析了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相关信息请参阅本站其他文章!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章