解决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  from render."错误

通常是因为以下两个原因:

  • render中返回一个函数引用而不是一个组件。
  • 使用 react router 路由作为 ,而不是} />

解决React报错Functions are not valid as a React child_第1张图片

这里有个例子来展示错误是如何发生的。

// App.js
/**
 * ⛔️ Functions are not valid as a React child.
 * This may happen if you return a Component instead of  from render.
 *  Or maybe you meant to call this function rather than return it.
 */
const App = () => {
  const getButton = () => {
    return ;
  };
  // ️ returning function not JSX element from render
  return 
{getButton}
; }; export default App;

上面代码片段的问题在于,我们从render方法中返回getButton函数,而不是返回真正的JSX元素。

调用函数

为了解决这种情况下的错误,我们可以调用该函数。

const App = () => {
  const getButton = () => {
    return ;
  };
  // ✅ now returning the actual button
  // added parenthesis () to call the function
  return 
{getButton()}
; }; export default App;

通过调用getButton函数,我们返回了button元素从而解决了该错误。

如果你正在尝试渲染一个真正的组件,确保将其用作而不是Component

const App = () => {
  const Button = () => {
    return ;
  };
  // ✅ Using component as 
); }; export default App;

另一个导致该错误的原因是,当我们为react router 路由传递一个元素时,比如

// ⛔️ wrong syntax

// ✅ right syntax
} />

在 react router v6 中,我们不向 Route 组件传递 children 属性,而是使用 element 属性。例如,} />

当使用react router时,请确保将应该为特定路由渲染的组件作为,而不是Component

总结

可以通过以下两种方式解决错误:

  • render中返回组件而不是函数。
  • 传递给路由中element属性的是,而不是Component

原文链接:bobbyhadz.com/blog/react-…

以上就是解决React报错Functions are not valid as a React child的详细内容,更多关于React 报错Functions valid的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(解决React报错Functions are not valid as a React child)