函数作为 React 子错误无效

函数作为 React 子错误无效

Functions are not valid as a React child error

错误“Functions are not valid as a React child. 如果您返回组件而不是<Component />从渲染中返回,则可能会发生这种情况。” 发生有 2 个常见原因:

  1. 从渲染中返回一个函数引用而不是一个组件。
  2. 使用 React 路由器路由<Route path="/about" element={About} />
    代替
    <Route path="/about" element={<About />} />.

函数作为反应子项无效

下面是错误如何发生的简单示例。

应用程序.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;

代码片段中的问题是我们getButton从 render 方法返回函数而不是返回实际的 JSX 元素。

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

应用程序.js
const App = () => { const getButton = () => { return <button>Click</button>; }; // ✅ now returning the actual button // added parentheses () to call the function return <div>{getButton()}</div>; }; export default App;

By calling the getButton function, we return the button element which solves
the error.

If you are trying to render an actual component, make sure to use it as
<Component /> and not Component.

App.tsx
const App = () => { const Button = () => { return <button>Click</button>; }; // ✅ Using component as <Button />, not Button return ( <div> <Button /> </div> ); }; export default App;

Another common cause of the “Functions are not valid as a React child” error is
when we pass an element to a react router route like
<Route path="/about" element={About} />.

App.js
// ⛔️ wrong syntax <Route path="/about" element={About} /> // ✅ right syntax <Route path="/about" element={<About />} />

In react router v6, instead of passing a children prop to the Route
components, we use the element prop, e.g.
<Route path="/about" element={<About />} />.

When using react router, make sure to pass the component that should be rendered
for the specific route as <Component /> and not Component.