关于react.js:React报错之Functions-are-not-valid-as-a-React-child

3次阅读

共计 1519 个字符,预计需要花费 4 分钟才能阅读完成。

注释从这开始~

总览

产生 ”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 />} />

这里有个例子来展现谬误是如何产生的。

// 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;

<Component />

另一个导致该谬误的起因是,当咱们为 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

总结

能够通过以下两种形式解决谬误:

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