反应:在地图循环中,如何在打印四列后中断表行?



如何打印以下带有数据列表的表结构? 假设我有以下城市列表。

cities = ['San Fransisco', 'Mumbai', 'Belarus', 'Kathmandu', 'Jakarta', 'Manila', 'Copenhagen', 'Tehran', 'Khartoum', 'Jeddah']

我需要在每打印四列后中断表行,如下所示:

<tr>
<td>San Fransisco</td>
<td>Mumbai</td>
<td>Belarus</td>
<td>Kathmandu</td>
</tr>
<tr>
<td>Jakarta</td>
<td>Manila</td>
<td>Copenhagen</td>
<td>Tehran</td>
</tr>
<tr>
<td>Khartoum</td>
<td>Jeddah</td>
</tr>

这是我尝试过的:

<table className="table">
<thead>
<tr>
<th>Delivery Location</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{cities && cities.map((zone, i) => { return (
{(i % 4 === 0) ? <tr key={i}> : null }
<td>{zone.name}</td>
{(i % 4 === 0) ? </tr> : null }
)})}
</tbody>
</table>

但是我的 IDE 显示多个语法错误。我还尝试在代码周围添加一个包装div,但我仍然收到错误。

您可以将数组简化为一个数组数组,每个数组具有 4 个元素,然后具有嵌套映射结构,例如

class App extends React.Component {
state = {
rcities: ['San Fransisco', 'Mumbai', 'Belarus', 'Kathmandu', 'Jakarta', 'Manila', 'Copenhagen', 'Tehran', 'Khartoum', 'Jeddah']
}
componentDidMount() {

const size = 4;
var rcities = [...this.state.rcities];
const res = rcities.reduce((acc, curr, i) => {
if ( !(i % size)  ) {    // if index is 0 or can be divided by the `size`...
acc.push(rcities.slice(i, i + size));   // ..push a chunk of the original array to the accumulator
}
return acc;
}, []);
this.setState({cities: res})
}
render() {
console.log(this.state.cities)
return (
<table className="table">
<thead>
<tr>
<th>Delivery Location</th>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
</thead>
<tbody>
{this.state.cities && this.state.cities.map((zone, i) => { return (
<tr key={i}>
{zone.map((city, index) => {
return    <td key={index}>{city}</td>
})}
</tr>

)})}

</tbody>
</table>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

最新更新