javascript React <div> 不能作为 <tr> 的子项出现警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47911216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React <div> cannot appear as a child of <tr> Warning
提问by lukegf
I am getting the following warnings in a React component:
我在 React 组件中收到以下警告:
The related code is the following:
相关代码如下:
import React, { PropTypes } from 'react';
import { Checkbox } from 'react-bootstrap';
const MyComponent = (params) => {
function onSelect(event) {
params.onSelect(event, params.data.id);
}
return (
<tr key={params.data.id}>
{params.isSelectable ? (
<Checkbox onChange={onSelect}>
<td>{params.data.firstName} </td>
<td>{params.data.lastName} </td>
</Checkbox>
) : (
<div>
<td>{params.data.firstName} </td>
<td>{params.data.lastName} </td>
</div>
)}
</tr>
);
};
};
If I remove the div tags, I get the following error:
如果删除 div 标签,则会出现以下错误:
Adjacent JSX elements must be wrapped in an enclosing tag
相邻的 JSX 元素必须包含在封闭标签中
I am new to React, so i am not quite clear on what is going on here. What's the problem and how can I fix it?
我是 React 的新手,所以我不太清楚这里发生了什么。有什么问题,我该如何解决?
Update: my React version is 15.3.2.
更新:我的 React 版本是 15.3.2。
回答by Abderrahmane TAHRI JOUTI
There are two problems with your code
你的代码有两个问题
- Only td and th are allowed inside tr
In React version < 15, you have to wrap tags in one element, when you try to render them. In React 16,you can now do the following :[ <td key={1}>{params.data.firstName} </td>, <td key={2}>{params.data.lastName} </td> ]instead of wrapping the
tds inside adiv
- tr 中只允许 td 和 th
在 React 版本 < 15 中,当您尝试渲染它们时,您必须将标签包装在一个元素中。在 React 16 中,您现在可以执行以下操作:[ <td key={1}>{params.data.firstName} </td>, <td key={2}>{params.data.lastName} </td> ]而不是将
tds包裹在 a 中div
I also suggest you extract your logic outside of the tr
我还建议您在 tr
回答by Ricardo Lopes
If you need to return several elements and can't have a wrapper (such as in this case), you have a new option as of React 16.2. Fragments:
如果你需要返回多个元素并且不能有一个包装器(比如在这种情况下),你有一个从 React 16.2 开始的新选项。片段:
<React.Fragment>
<td>{params.data.firstName} </td>
<td>{params.data.lastName} </td>
</React.Fragment>
Or, you might be able to simplify it as:
或者,您可以将其简化为:
<>
<td>{params.data.firstName} </td>
<td>{params.data.lastName} </td>
</>
The fragments won't resolve to any HTML element, so the <td>s will be direct children of your <tr>.
这些片段不会解析为任何 HTML 元素,因此<td>s 将是您的<tr>.


