我已经使用了for
循环并在click函数中给出了它的值,这样我就可以在点击座位时获得座位号,但每次点击座位时我只获得for循环的最后一个编号。谁能告诉我如何获得每个座位的座位号?API数据是
var seats = [
{ name: "Premium", seattotal: "15", cost: "250", id: "1" },
{ name: "Club", seattotal: "30", cost: "150", id: "2" },
{ name: "Diamond", seattotal: "25", cost: "170", id: "3" },
{ name: "Gold", seattotal: "20", cost: "170", id: "4" },
];
function handleClick(seatnumber, seatamount, seatname) {
alert(seatnumber + " " + count + " " + seatamount + " " +
seatname);
setIsActive((oldArray) => [...oldArray, seatnumber]);
setAmount((oldamt) => parseFloat(oldamt) + parseFloat(seatamount));
if (selectseat.includes(seatname) === false) {
setSelectSeat((oldArray) => [...oldArray, seatname]);
}
console.log(isActive + " " + selectseat);
}
function seat(totalseat, seatcost, seatname) {
var seats = [];
for (var i = 1; i <= totalseat; i++) {
seats.push(
i % 5 ? (
<TouchableOpacity
key={i}
style={isActive == i ? styles.activeseat : styles.seat}
onPress={(event) => handleClick(i, seatcost, seatname)}
>
<Text style={{ fontSize: 10 }}>{i}</Text>
</TouchableOpacity>
) : (
<TouchableOpacity
key={i}
style={
isActive == i
? { ...styles.activeseat, marginRight: 30 }
: { ...styles.seat, marginRight: 30 }
}
onPress={(event) => handleClick(i, seatcost, seatname)}
>
<Text style={{ fontSize: 10 }}>{i}</Text>
</TouchableOpacity>
)
);
}
totalseat != 0
? seats.push(
<View
key={i}
style={{ backgroundColor: "white", height: 20, width:
"100%" }}
></View>
)
: "";
return seats;
}
const allseatui = Object.keys(seats).map((key) => {
const varseat = seat(
seats[key].seattotal,
seats[key].cost,
seats[key].name
);
if (seats[key].name != undefined) {
return (
<View key={seats[key].id}>
<Text style={{ margin: 12, fontSize: 14, color: "grey" }}>
{seats[key].name} Rs {seats[key].cost}
</Text>
<View
style={{
flexDirection: "row",
flexWrap: "wrap",
}}
>
{varseat}
</View>
</View>
);
}
});
2条答案
按热度按时间vlju58qv1#
问题
i
被声明为var
,并在填充seats
数组时的for循环中发生变化。因为这是一个常规的for循环,所以每个onPress
handleClick
回调处理程序正在访问的作用域中只有一个i
变量引用。在最后一次迭代中,i
再次递增,并且由于它现在严格大于totalseat
,所以退出循环。当totalseat
等于"20"
且退出条件为i <= 20
时,将存在20次迭代且i
在退出时将等于21。溶液
使用
Array.prototype.map
函数将长度为totalseat
的数组Map到要保存到seats
数组中的JSX。.map
回调函数将接收当前Map索引值的副本。l0oc07j22#
使用Map代替For循环。for循环在循环运行时会改变i值