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。” 有 2 个常见原因:

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

下面是一个产生上述错误的示例

/**
 * ⛔️ 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;

React 中的 Functions are not valid as a React child 错误

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

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

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;

通过调用 getButton 函数,我们返回解决错误的按钮元素。

如果您尝试渲染一个实际的组件,请确保将其用作 <Component /> 而不是 Component。

const App = () => {
  const Button = () => {
    return <button>Click</button>;
  };

  // ✅ Using component as <Button />, not Button
  return (
    <div>
      <Button />
    </div>
  );
};

export default App;

“Functions are not valid as a React child”错误的另一个常见原因是当我们将元素传递给反应路由器路由时,例如 <Route path=”/about” element={About} />。

// ⛔️ wrong syntax
<Route path="/about" element={About} />

// ✅ right syntax
<Route path="/about" element={<About />} />

在 react router v6 中,我们没有将 children 属性传递给 Route 组件,而是使用 element 属性,例如 <Route path="/about" element={<About />} />

使用 react router 时,请确保将应为特定路由呈现的组件传递为 <Component /> 而不是 Component。