我有一个复杂的<table>
,与另一个JavaScript框架(淘汰赛)有很多绑定。我正在尝试将其一部分转换为React。
<table>
<tbody id="lots_of_legacy_knockout"> ... </tbody>
<tbody id="I_want_this_in_React"></tbody>
</table>
但是,这试图将<tbody>
根元素放入<tbody>
容器中:
const Tbody = () => (
<tbody>
<tr />
<tr />
<tr />
</tbody>
);
ReactDOM.render(
<Tbody />,
document.getElementById('I_want_this_in_React')
);
这会导致错误,因为React想要一个唯一的根元素:
const Tbody = () => ([
<tr />,
<tr />,
<tr />,
]);
ReactDOM.render(
<Tbody />,
document.getElementById('I_want_this_in_React')
);
如何在不重写React中的整个根<table>
元素的情况下完成此操作?
是否有一种方法可以将反应根和反应容器组合?
您现在可以使用React.Fragment
:
const Tbody = () => (
<React.Fragment>
<tr />
<tr />
<tr />
</React.Fragment>
);
ReactDOM.render(
<Tbody />,
document.getElementById('I_want_this_in_React')
);
这将导致:
// Invalid HTML
<tbody id="I_want_this_in_React">
<tbody>
<tr></tr>
<tr></tr>
<tr></tr>
</tbody>
</tbody>
无效的html。
由于React需要渲染的组件才具有零兄弟姐妹,因此我认为没有一种方法可以使用React进行操作。
例如,您需要用 html元素包装<Tr />
组件,这也不是有效的html。
// Invalid HTML
<tbody>
<span>
<tr></tr>
<tr></tr>
<tr></tr>
</span>
</tbody>
有没有一种方法可以将旨在反应为自己的<table>
的<tbody>
分开?
如果是这样,您可以做这样的事情:
html:
<table id="lots_of_legacy_knockout">
<tbody>...</tbody>
</table>
<table id="I_want_this_in_React"></table>
React:
const Tbody = () => (
<tbody>
<tr />
<tr />
<tr />
</tbody>
);
ReactDOM.render(
<Tbody />,
document.getElementById('I_want_this_in_React')
);
或嵌套<table>
:
html:
<table id="lots_of_legacy_knockout">
<tbody>...</tbody>
<table id="I_want_this_in_React"></table>
</table>
React:
const Tbody = () => (
<tbody>
<tr />
<tr />
<tr />
</tbody>
);
ReactDOM.render(
<Tbody />,
document.getElementById('I_want_this_in_React')
);