【问题标题】:How to get rid of "Functions are not valid as a React child" warning in React app如何摆脱 React 应用程序中的“Functions are not valid as a React child”警告
【发布时间】:2020-06-01 09:21:36
【问题描述】:

我是 React 新手,我正在借助 Hooks 在 React 中开发简单的 CRUD 应用程序。
该应用程序有两个表单组件AddUserFormEditUserForm,分别添加和编辑用户列表。还有一个组件显示用户列表(但我没有收到警告)。
一切正常,但我的浏览器控制台中有以下警告消息:
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.

这是我在 App.js 文件中呈现子组件的方式。 (我用红色箭头标记了我有警告的行)

更新 以下是我在AddUserForm 组件中处理表单的方式:

return (
 <Fragment>
  <form> // line 15, here I have warning as well
    onSubmit=
    {event => {
      event.preventDefault();
      if (!user.name || !user.username) return;

      props.addUser(user);
      setUser(initialFormState);
    }}
    <label>Name</label>
    <input type='text' name='name' value='' onChange={handleInputChange} />
    <label>Username</label>
    <input
      type='text'
      name='username'
      value=''
      onChange={handleInputChange}
    />
    <button>Add new user</button>
  </form>
 </Fragment>
);

我检查了一些编写的解决方案,例如 here,但没有一个对这个问题有帮助。
你能告诉我我做错了什么吗?

【问题讨论】:

  • 您的控制台会警告您有关 AddUserForm 组件,它看起来像那里的问题。
  • 我刚刚添加了有问题的 AddUserForm 组件的代码。

标签: javascript reactjs react-hooks react-component


【解决方案1】:

我认为这只是一个错字:

<form> // You just closed form element, so 
onSubmit=
{event => { // this is a function returned as a React child
  event.preventDefault();
  if (!user.name || !user.username) return;

  props.addUser(user);
  setUser(initialFormState);
}}
<label>Name</label>
<input type='text' name='name' value='' onChange={handleInputChange} />
<label>Username</label>
<input
  type='text'
  name='username'
  value=''
  onChange={handleInputChange}
/>
<button>Add new user</button>

应该是这样的:

<form // Note the missing >
onSubmit=
{event => { // this is a function returned as a React child
  event.preventDefault();
  if (!user.name || !user.username) return;

  props.addUser(user);
  setUser(initialFormState);
}}> // form opening tag closed here

这实际上不是 React 问题,而是导致 React 抛出错误的无效 HTML,因为它无法解析和呈现 JSX。

【讨论】:

    猜你喜欢
    • 2023-01-17
    • 2020-01-12
    • 2021-06-29
    • 1970-01-01
    • 2023-01-25
    • 2021-08-02
    • 1970-01-01
    • 2020-12-09
    • 2021-11-08
    相关资源
    最近更新 更多