React报错之Functions are not valid as a React child
2023-02-18 16:41:38 时间
正文从这开始~
总览
产生"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
。
相关文章
- [PHP] php作为websocket的客户端实时读取推送日志文件
- [MySQL] in 子查询出现DEPENDENT SUBQUERY问题
- [MySQL] 导入数据时防止出现乱码
- [MySQL] group by 聚合函数的原理和聚合限制原因SELECT list is not in GROUP BY clause and contains nonaggregated column
- [PHP] websocket协议的生成
- [MySQL]mysql的ANY_VALUE()函数 解决 ONLY_FULL_GROUP_BY 模式
- [PHP] 框架中.env文件的加载过程
- [PHP] PHP7已经删除了preg_replace的e修饰符
- [日常]解决Connection to `ssl://pecl.php.net:443' failed
- [日常]k8s的前世今生
- [日常]windows下kill进程工具taskkill
- [CSS] 纯CSS的前端图标icon库并且修改大小和颜色
- [PHP] php中的索引数组和数组顺序问题
- [PHP] RBAC权限与审批流的简单数据库构想
- [日常] 修改编辑word中的页眉页脚
- [PHP] socket客户端时的超时问题
- [nginx]配置nginx支持websocket解决返回400错误问题
- [nginx]配置nginx支持websocket解决返回400错误问题
- [PHP] php5.3之前-php5.3-php7垃圾回收机制的进化
- [PHP] include语句的注意事项