当输入被声明为无效时,在React中添加一个复选框

Adding a checkbox in React when input is declared void

本文关键字:添加 复选框 一个 React 声明 输入 无效      更新时间:2023-09-26

这是我的问题,我有一个列表正在呈现并返回,如下所示:

return (
        <li className="itemsInList">{this.props.children}</li>
    )

但我想添加一个复选框,所以如果我这样做:

return (
        <input type="checkbox" className="itemsInList">{this.props.children}</input>
    )

但随后显示错误:arning: input is a void element tag and must not have children

如何绕过此错误,将它们显示在带有复选框的列表中?

这个错误很明显。输入不允许有子项。这是HTML定义的一部分。查看此

我猜您希望为this.props.children中的每个项目都有一个复选框。所以我要做的是保留<li>并将<input>放在里面。

return (
  <ul className="itemsInList">
    {this.props.children.map(function(child) { 
      return (<li className='child'>
        <input type='checkbox'>
        <label>{child.someAttribute}</label>
      </li>);
    }} 
  </ul>
);

请注意,您必须为循环中的每个<li>指定一个唯一的key属性。

希望能有所帮助。