我正在try 创建数组的空array.
该 struct 需要是每行一个数组(比方说3),然后是每行x个列数(比方说5),例如:
[
[false, false, false, false, false],
[false, false, false, false, false],
[false, false, false, false, false],
]
当在TouchableOpacity
组件上单击onPress
时,应该发生的情况是单个列的背景切换为红色,例如,如果我单击第二行中的第二列,则数组应变为以下内容:
[
[false, false, false, false, false],
[false, true, false, false, false],
[false, false, false, false, false],
]
但如果我这样做,会发生什么呢?
[
[false, true, false, false, false],
[false, true, false, false, false],
[false, true, false, false, false],
]
每行中的第二项(或我单击的任何列)正在更改,而不是特定行中的特定列.我不知道为什么.
export const = ({
numberOfRows,
numberOfCols,
dimens
}: Props) => {
const [rows, setRows] = useState<boolean[][]>(Array(numberOfRows).fill(Array(numberOfCols).fill(false)));
const handleOnPress = (rowIdx: number, colIdx: number) => {
const rowsData = [...rows];
rowsData[rowIdx][colIdx] = !rowsData[rowIdx][colIdx];
setRows(rowsData);
};
return (
<View style={{ width: dimens.width, height: dimens.height }}>
{rows.map((row, rowIdx) => {
return (
<View key={Math.random()} style={{ display: 'flex', flexDirection: 'row', marginBottom: 20 }}>
{row.map((_col, colIdx) => (
<TouchableOpacity key={Math.random()} style={{ backgroundColor: rows[rowIdx][colIdx] ? 'red' : '', borderWidth: 1, flex: dimens.width / 5, height: 50 }} onPress={() => handleOnPress(rowIdx, colIdx)}>{colIdx}</TouchableOpacity>
))}
</View>
);
})}
</View>
);
};