我正在尝试在 React 中构建一个可重用的表格组件,但到目前为止在渲染我的 <td>
时运气不佳。
我正在从 TableList
传递我需要的 Prop 我的组件 TableRow
像这样的组件:
const TableList = props => {
const { listData, listHeaders } = props;
return (
<table className="table table-striped">
<thead>
<tr>
{listHeaders.map(header => (
<th scrope="col" key={header}>
{header}
</th>
))}
<th scope="col" />
</tr>
</thead>
<tbody>
{listData.map(data => (
<TableRow
key={data.id}
data={data}
handleClick={props.handleClick}
/>
))}
</tbody>
</table>
);
};
并在TableRow
我可以很好地迭代我的 JSON 对象,但我的元素没有呈现。我没有收到任何错误,但我的 <tr>
DOM 中的元素没有子元素。这是我的 TableRows
组件:
const TableRow = props => {
const { data } = props;
return (
<tr>
{Object.keys(data).forEach(function(item) {
console.log(data[item]); // This prints out my JSON objects just fine
<td key={item}>data[item]</td>; // But this element isn't rendering in the DOM
})}
</tr>
);
};
我已经尝试将我的 JSON 对象分配给 .map()
的数组导航也一样,得出了相同的结果。我也试过移动各种元素,比如 <tbody>
和 <tr>
在组件树上上下移动都没有运气。
最佳答案
您必须从循环中返回 JSX 元素。喜欢
return (
<tr>
{Object.keys(data).map(function(item) {
console.log(data[item]); // This prints out my JSON objects just fine
return <td key={item}>data[item]</td>; // But this element isn't rendering in the DOM
})}
</tr>
);
Array#forEach返回 undefined
。目前,您正在呈现 undefined
。您可以使用 Array#map用于转换输入数组并返回一个数组。
关于javascript - 遍历 JSON 和渲染表元素没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55216233/