gpt4 book ai didi

javascript - 在 React 中循环遍历 和

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:21 25 4
gpt4 key购买 nike

我试图在我的数组中创建一个循环,并为每次传递创建一个表行。但是,我收到错误 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>

)}

最佳答案

问题是 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 = "")
}
}

然后在渲染内部调用状态,

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>
)}

关于javascript - 在 React 中循环遍历 <tr> 和 <td>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com