我试图通过数组创建一个循环,并为每次通过创建一个表行。但是,我收到一个错误Expected Expression
,但不确定为什么。有人有什么想法吗?另外,我也不太确定为什么for循环也可以用作函数参数,并且说明也很棒。下面是我的代码。
function FormTable(props){
/**
* props = allStations
*/
return(
<table className="form__table">
<thead>
<tr>
<th>Departing Station</th>
<th>Arriving Station</th>
<th colSpan={2}>Departure Time</th>
</tr>
</thead>
<tbody>
{ /**
this self-executing invoked function (IIFE)
is going to loop through all stations and create
table data. The reason for this IIFE is because you cannot perform
stright loops in JSX? Gotta look into it more.
i = 1 b/c stationIndex[0] = "WarmToDaly" aka property name
*/}
{( () => {
props.forEach((stationIndex) => {
<tr className="form__table-row">
for(let i = 1; i < this.stationIndex.length; i++){
for(let j = 0; j < stationIndex[i][j].length; j++){
}
}
</tr>
})
})()}
</tbody>
</table>
)}
答案 0 :(得分:2)
问题是forEach
不返回任何内容(即返回未定义)。因此,最好使用map
return(
<table className="form__table">
<thead>
<tr>
<th>Departing Station</th>
<th>Arriving Station</th>
<th colSpan={2}>Departure Time</th>
</tr>
</thead>
<tbody>
{
props.map((stationIndex) => {
return <tr className="form__table-row">
stationIndex.map(()=>{
//your code.......
})
</tr>
})
}
</tbody>
</table>
)}
如果您想forEach
componentDidMount(){
props.forEach((stationIndex) => {
var cells = ""
for(let i = 1; i < this.stationIndex.length; i++){
for(let j = 0; j < stationIndex[i][j].length; j++){
cells += "<td>"+{your_data}+"</td>"
}
}
const row = "<tr className='form__table-row'>" + cells + "</tr>"
this.setState({items:[...this.state.items, row]},() => cells = "")
}
}
然后在render内调用状态,
return(
<table className="form__table">
<thead>
<tr>
<th>Departing Station</th>
<th>Arriving Station</th>
<th colSpan={2}>Departure Time</th>
</tr>
</thead>
<tbody>
{this.state.items}
</tbody>
</table>
)}
答案 1 :(得分:0)
如果我理解正确,props
是包含您要呈现的表单元格数据的多维数组的数组。
渲染道具的一种方法是先将forEach()
替换为map()
,将prop
中的每个项目映射到可渲染的<tr>
元素(将包含<td>
单元格)。
要获取每一行的<td>
元素,您可以迭代map函数中的stationIndex
项并将<td>
元素的数组收集到本地cells
数组中。
此<tr>
的结果stationIndex
将与cell数组的内容一起呈现,如下所示:
{
props.map((stationIndex) => {
const cells = [];
/* Iterate the multi-dimensional stationIndex array and
collect an array of <td> elements */
for(let i = 1; i < stationIndex.length; i++){
for(let j = 0; j < stationIndex[i][j].length; j++){
cells.push(<td>{ stationIndex[i][j] }</td>)
}
}
/* Render the cell (td) elements into the tr that is
the result of this stationIndex mapping */
return <tr className="form__table-row">{ cells }</tr>;
})
}