警告:validateDOMNesting(...): <div> 不能作为<tbody>的子元素出现

15

我正在React中创建一个表格(我是React的新手),但CategoryData是否可以使用还是应该使用其他东西?它没有正确创建单元格,即它创建的单元格与来自父级的<th>不对齐,并且它们根本没有单元格边框。它还会出现以下警告:

Warning: validateDOMNesting(...): <div> cannot appear as a child of <tbody>. See Param > tbody > Row > div.
Warning: validateDOMNesting(...): <tr> cannot appear as a child of <div>. See Row > div > tr.
Warning: validateDOMNesting(...): <tr> cannot appear as a child of <div>. See CategoryData > div > tr.

我不确定为什么会出现这些警告,以及为什么表格单元格(来自CategoryData)没有对齐且没有单元格边框。有什么正确的做法吗?

代码:

var Param = React.createClass({

    getInitialState: function() {
        return {
            isLoading: true,
            panelTitle: "",
            data: [],
            categories: []
        }
    },

    updateState: function() {
        var that = this;
        var categories = new Set();
        rest.getParameters('service').then(function (results) {
            for (var i = 0; i < results.data.length; i++) {
                categories.add(results.data[i].category);
            }
            that.setState({
                data: results.data,
                categories: Array.from(categories)
            })
        }).catch(function (err) {
            console.error('rest.getParameters(): ', err);
            that.setState({
                isLoading: true,
                data: [],
                categories: []
            })
        });
    },

    componentDidMount: function() {
        this.updateState();
    },

    render: function() {
      return (
        <Panel className="panel-info" header={<h4 className="panel-title">Service Config</h4>}>
            <div>
                <table className="table table-striped table-bordered table-hover table-condensed table-responsive">
                    <thead>
                        <tr>
                            <th className="col-lg-2 text-center">AMP Name</th>
                            <th className="col-lg-2 text-center">Athena Name</th>
                            <th className="col-lg-2 text-center">Description</th>
                            <th className="col-lg-1 text-center">Default</th>
                            <th className="col-lg-1 text-center">Min Value</th>
                            <th className="col-lg-1 text-center">Max Value</th>
                            <th className="col-lg-1 text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.categories.map((category, index) =>
                            <th colSpan="7" key={index} style={{'textAlign':'left', 'paddingLeft':'5px', 'backgroundColor': '#D3D0CF'}}>{this.state.category}</th>
                            this.state.data.map((row, i) =>
                                if (row.category === category) {
                                    <tr key={i}>
                                        <td className="col-lg-2 text-center">{row.name}</td>
                                        <td className="col-lg-2 text-center">{row.alias}</td>
                                        <td className="col-lg-2 text-center">{row.description}</td>
                                        <td className="col-lg-1 text-center">{row.default_value}</td>
                                        <td className="col-lg-1 text-center">{row.min_value}</td>
                                        <td className="col-lg-1 text-center">{row.max_value}</td>
                                        <td className="col-lg-1 text-center">Action</td>
                                    </tr>
                                }
                            )  
                        )}
                    </tbody>
                </table>
            </div>
        </Panel>
    );
  }
});

2
你的 tr 标签被包含在 div 标签中。 - Frank Fajardo
2
除非 <div><td><th> 的直接子元素,否则不能将其放在 <table> 中。你的 <div><tbody> 的子元素。你可能需要重新设计 var Row,不要将 <div> 渲染为外部容器元素 :) - Obsidian Age
1
只需从你的“Row”中删除<div>即可。 如果你想要一个<div>,它可能会放在“Panel”中。这取决于你希望最终的结构是什么样子。但是,是的,在你的行中返回<div><tr>...肯定是无效的 :) - Obsidian Age
https://dev59.com/pV8e5IYBdhLWcg3whqzl#25647392 - btzr
截至2019年3月,您的问题看起来很令人困惑,因为您的代码不再包括导致原始错误的“Row”和“CategoryData”组件。当前代码的问题是您将<th>元素渲染到了<tr>元素外部。<th>应该始终是<tr>的子元素。 - carpiediem
显示剩余4条评论
2个回答

5

我会将“th”更改为“tr”,因为我相信如果在“tbody”内添加“th”,React会发出警告。

let finalList = []
this.state.categories.forEach( (cat, index) => {
   finalList.push(<tr...>{this.state.category}</tr>)
   this.state.data.forEach( (row, index) => {
      if(row.category === cat){
         finalList.push(
             <tr key={i}>
                 <td className="col-lg-2 text-center">{row.name}</td>
                 <td className="col-lg-2 text-center">{row.alias}</td>
                 <td className="col-lg-2 text-center">{row.description}</td>
                 <td className="col-lg-1 text-center">{row.default_value}</td>
                 <td className="col-lg-1 text-center">{row.min_value}</td>
                 <td className="col-lg-1 text-center">{row.max_value}</td>
                 <td className="col-lg-1 text-center">Action</td>
             </tr>
          )
      }
   })
})

警告:我建议避免使用表格,可以使用CSS网格布局,它更加灵活并且被广泛支持。


4

编辑:从版本16.0.0开始,在React中,您可以使用React.Fragment从渲染中返回多个元素。

<tbody>
    {
        this.state.categories.map((category, index) => {
            var innerData = this.state.data.map((row, i) => {
                if (row.category === category) {
                    return (
                        <tr key={i}>
                            <td className="col-lg-2 text-center">{row.name}</td>
                            <td className="col-lg-2 text-center">{row.alias}</td>
                            <td className="col-lg-2 text-center">{row.description}</td>
                            <td className="col-lg-1 text-center">{row.default_value}</td>
                            <td className="col-lg-1 text-center">{row.min_value}</td>
                            <td className="col-lg-1 text-center">{row.max_value}</td>
                            <td className="col-lg-1 text-center">Action</td>
                        </tr>
                    )
                }
                return null
            })

            return (
              <React.Fragment>
                <th colSpan="7" key={index} style={{
                    'textAlign': 'left',
                    'paddingLeft': '5px',
                    'backgroundColor': '#D3D0CF'
                }}>{this.state.category}</th>,
                {innerData}
              </React.Fragment>    
            )
        })
    }
    </tbody>

v16之前

通过使用 JSX语法糖,可以将多个元素从组件中返回,将它们写成一个以逗号分隔的数组形式即可。

<tbody>
{
    this.state.categories.map((category, index) => {
        var innerData = this.state.data.map((row, i) => {
            if (row.category === category) {
                return (
                    <tr key={i}>
                        <td className="col-lg-2 text-center">{row.name}</td>
                        <td className="col-lg-2 text-center">{row.alias}</td>
                        <td className="col-lg-2 text-center">{row.description}</td>
                        <td className="col-lg-1 text-center">{row.default_value}</td>
                        <td className="col-lg-1 text-center">{row.min_value}</td>
                        <td className="col-lg-1 text-center">{row.max_value}</td>
                        <td className="col-lg-1 text-center">Action</td>
                    </tr>
                )
            }
            return null
        })

        return ([
            <th colSpan="7" key={index} style={{
                'textAlign': 'left',
                'paddingLeft': '5px',
                'backgroundColor': '#D3D0CF'
            }}>{this.state.category}</th>,
            [...innerData]
        ])
    })
}
</tbody>

此外,在使用映射函数中的if语句时,必须将其放在返回语句之外。如果您这样做:{this.state.categories.map((category, index) => <tr>...,则箭头后面的任何内容都被认为是返回的一部分,因此内部映射函数中的if语句会导致错误。
关于返回多个元素,React Github页面上有一个issue ,请阅读其中的详细信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接