前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React报错之Functions are not valid as a React child

React报错之Functions are not valid as a React child

作者头像
chuckQu
发布2022-08-19 16:43:31
2.5K0
发布2022-08-19 16:43:31
举报
文章被收录于专栏:前端F2E前端F2E

原文链接:https://bobbyhadz.com/blog/react-functions-are-not-valid-as-react-child[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

总览

产生"Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render."错误,通常是因为以下两个原因:

  1. render中返回一个函数引用而不是一个组件。
  2. 使用 react router 路由作为<Route path="/about" element={About} /> ,而不是<Route path="/about" element={<About />} />

functions-are-not-valid-as-react-child.png

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

代码语言:javascript
复制
// 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元素。

调用函数

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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} />

代码语言:javascript
复制
// ⛔️ 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

总结

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

  1. render中返回组件而不是函数。
  2. 传递给路由中element属性的是<Component />,而不是Component

参考资料

[1]

https://bobbyhadz.com/blog/react-functions-are-not-valid-as-react-child: https://bobbyhadz.com/blog/react-functions-are-not-valid-as-react-child

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-08-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端F2E 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 总览
  • 调用函数
  • 总结
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档