React - table 创建不正确

React - table created incorrectly

我在 React 中有一个 table,用户可以在其中添加可变数量的行。

<div>
    <table class="table table-condensed table-bordered">
        <tr>
            <th>List Names</th>
            <th>List Full Names</th>
            <th>List Descriptions</th>
        </tr>
        {this.displayTableBody()}
    </table>

    <button style={{display:'inline-block'}} type="button" 
            className="btn btn-primary btn-small" onClick={this.addList}>
        <span className="glyphicon glyphicon-plus"></span>
    </button>
</div>

行由displayTableBody方法添加:

displayTableBody: function() {
    var rows = Array.apply(null, Array(this.state.rowNr)).map(
        function(e1, index) {
            return <ListInput key={index} ref={index}/>
        }
    );
    return(<div>{ rows }</div>);
}

一行由 ListInput 组件组成,具有以下 render 方法:

render: function() {
    return (
        <tr>
            <td>{this.displaySimpleInputField(
                "List Name(<15 characters - A-Z, 0-9 and _ only)", this.setListName, "input")}</td>
            <td>{this.displaySimpleInputField(
                "List Full Name(<75 characters)", this.setListFullName, "input")}</td>
            <td>{this.displaySimpleInputField(
                "List Description(<225 characters)", this.setListDescription, "input")}</td>
        </tr>
    )
}

但是,当我添加一行时,它位于 table header:

之上

您将 div 元素直接插入到 table 中,这是不正确的 html,它确实破坏了布局,placing that element at the top of the table

我建议按如下方式重组您的代码,并考虑使用 times function from lodash:

displayTableBody: function() {
  var rows = times(this.state.rowNr).map(
    function(index) {
      return <ListInput key={index} ref={index}/>
    }
  );
  return(<tbody>{ rows }</tbody>);
}

还有 table

<table class="table table-condensed table-bordered">
  <thead>
    <tr>
      <th>List Names</th>
      <th>List Full Names</th>
      <th>List Descriptions</th>
    </tr>
  </thead>
  {this.displayTableBody()}
</table>

当使用 tables 时,写有效的 HTML 是非常重要的,否则你会得到像这样奇怪的结果。具体来说,table 的正确结构有点像这样:

<table>
  <thead>
    <tr><th></th></tr>
  </thead>
  <tbody>
    <tr><td></td></tr>
  </tbody>
</table>

具体来说,我很确定您不能像使用 displayTableBody 方法那样将 div 直接放在 table 中。尝试重写您的组件以遵循 HTML standard,我相信这就是导致您出现问题的原因。