react:validateDOMNesting:#text 不能作为 <tr> 的孩子出现

IT技术 reactjs warnings
2021-04-28 12:20:04

你能解释一下为什么react显示警告Warning: validateDOMNesting(...): #text cannot appear as a child of <tr>. See Router > RouterContext > CarWashPage > AllCarWashTable > tr > #text.吗?我在标签内看不到任何文字tr

呈现表格的代码

export default class AllCarWashTable extends React.Component{

constructor(props) {
    super(props);
    this.generateHeaders = this.generateHeaders.bind(this);
    this.generateRows = this.generateRows.bind(this);
};

static propTypes = {
    cols : React.PropTypes.array.isRequired,
    rows : React.PropTypes.array.isRequired
}

generateHeaders() {
    let cols = this.props.cols;  // [{key, label}]
    return cols.map(function(colData) {
        return <th key={colData.key}> {colData.label} </th>;
    });
}

generateRows() {
    let cols = this.props.cols,  // [{key, label}]
        data = this.props.rows;
    if (this.props.rows.length > 0) {
        return data.map(function(item) {
            var cells = cols.map(function(colData) {
                return <td key={colData.key}> {item[colData.key]} </td>;
            });
            return <tr key={item.id}> {cells} </tr>;
        });
    }
}

render(){
    let headers = this.generateHeaders();
    let rows = this.generateRows();

    return (
         <table className="table table-hove">
             <thead>
                <tr>
                    {headers}
                </tr>
             </thead>
             <tbody>
                    {rows}
             </tbody>

         </table>
    )
}
}

最后,我的表具有以下结构

在此处输入图片说明

哪里有问题?

4个回答

问题是这一行中的空格:

return <tr key={item.id}> {cells} </tr>;

这可能看起来很傻,但您实际上是在渲染单元格和一些空白(即文本)。它应该是这样的:

return <tr key={item.id}>{cells}</tr>;

当使用逻辑 AND 短路&&来显示/隐藏条件行时,也会发生这种情况

{
  foo && (<tr><td>{foo}</td></tr>)
}

将其更改为三元a ? b : c形式,其中 cnull将修复它

{
  foo ? (<tr><td>{foo}</td></tr>) : null
}

在我的情况下,''输出是空的(里面没有空间)

<tbody>
  {this.props.orders.map(
    order =>this.props.selectedAgent === order.agent ? 
      <Row item={order} key={ order._id } /> : ''
    )
  }
</tbody>

的伎俩:

<tbody>
  {this.props.orders.map(
    order =>this.props.selectedAgent === order.agent ? 
      <Row item={order} key={ order._id } /> : null
    )
  }
</tbody>

在我的情况下,接受的答案不是根本原因。当我在<th>标记后发表评论时,我收到了同样的警告当我删除评论时,警告消失了。

const TableHeaders = (props) => (
  <tr>
    <th>ID</th> {/* TODO: I had a comment like this */}
  </tr>
)

编辑:删除之间的空间</th>,并{/*也将这样的伎俩。