反应:validateDOMNesting:#text 不能作为 <tr> 的子项出现

新手上路,请多包涵

你能解释一下为什么反应显示警告 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>
    )
}
}

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

在此处输入图像描述

问题出在哪里?

原文由 Bizon4ik 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 774
2 个回答

问题是这一行中的空格:

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

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

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

原文由 tobiasandersen 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

将其更改为三进制 a ? b : c 形式 c 是 null 将修复它

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

原文由 Kevin Law 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进