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

The*_*ane 1 javascript checkbox reactjs

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

return (
        <li className="itemsInList">{this.props.children}</li>
    )
Run Code Online (Sandbox Code Playgroud)

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

return (
        <input type="checkbox" className="itemsInList">{this.props.children}</input>
    )
Run Code Online (Sandbox Code Playgroud)

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

如何解决此错误以在带有复选框的列表中显示它们?

nbe*_*ezs 6

嗯,错误非常清楚.输入不允许有孩子.这是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>
);
Run Code Online (Sandbox Code Playgroud)

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

希望有所帮助.