[英]validateDOMNesting(...): <tr> cannot appear as a child of <div>
I'm trying to get this work:我正在努力完成这项工作:
Orders:订单:
render () {
const orders = this.state.orders.map((order, index) => <OrderRow order={order} key={index}/>);
return (
<table>
<tbody>
{orders}
</tbody>
</table>
);
}
OrderRow:订单行:
render () {
return (
<tr>
<td>{this.props.order.number}</td>
<td>{this.props.order.products}</td>
<td>{this.props.order.shippingDate}</td>
<td>{this.props.order.status}</td>
</tr>
);
}
But still getting this error:但仍然收到此错误:
Warning: validateDOMNesting(...): <tr> cannot appear as a child of <div>.
See Orders > div > OrderRow > tr.
Any ideas how to fix it?任何想法如何解决它?
Wrap your OrderRow
<tr>
in <tbody>
as explained in issue here , Browsers need the <tbody>
tag.将您的
OrderRow
<tr>
包裹在<tbody>
如问题here中所述,浏览器需要<tbody>
标签。 If it is not in your code, then the browser will automatically insert it.如果它不在您的代码中,那么浏览器会自动插入它。 This will work fine on first render, but when the table gets updated, then the DOM tree is different from what React expects.
这将在第一次渲染时正常工作,但是当表更新时,DOM 树与 React 期望的不同。 This can give strange bugs, therefore React warns you to insert the
<tbody>
.这可能会产生奇怪的错误,因此 React 会警告您插入
<tbody>
。
OrderRow订单行
render () {
return (
<table>
<tbody>
<tr>
<td>{this.props.order.number}</td>
<td>{this.props.order.products}</td>
<td>{this.props.order.shippingDate}</td>
<td>{this.props.order.status}</td>
</tr>
</tbody>
</table>
);
}
Something like this:像这样的东西:
render() { return ( <table> <tbody> {this.state.orders.map((order, index) => { <tr index={index}> <td>{order.number}</td> <td>{order.products}</td> <td>{order.shippingDate}</td> <td>{order.status}</td> </tr> })} </tbody> </table> ); }
Or more elegant:或者更优雅:
render () { return ( <table> <tbody> {this.state.orders.map((order, index) => ( return (<OrderRow order={order} key={index} />); )} </tbody> </table> ); }
它将tr
渲染为div
,因此请改用.map()
:)
Could you try something more automatic?你能试试更自动化的东西吗?
render() {
return (
<table>
<tbody>
{this.state.orders.map((order, index) => {
<tr index={index}>
{Object.keys(order).map(function(key,id) {
return (<td key={id}>{order[key]}</td>)
})}
</tr>
}}
</tbody>
</table>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.