【发布时间】:2021-07-06 02:12:23
【问题描述】:
我正在使用'@react-native-community/checkbox',因为我正在从数据库中检索数据并使用 map 函数将其渲染为带有复选框的复选框,问题是当我选中一个框时,所有框都已选中,而当我取消选中时相同
问题在于每个复选框的状态,但我不知道如何处理它,因为我只想选中 sleeted 复选框并将其所有数据放入一个数组中以供进一步处理。
这里是我渲染为复选框的数据:
{"id": "12345", "price": 5, "text": "Reload"}
这是map函数的代码:
{data.map((b, index) => {
return (
<View key={b.id} style={{ flex: 1, flexDirection: 'column', width: windowWidth, paddingLeft: 15, paddingRight: 15 }}>
<View style={{ flexDirection: 'row-reverse', alignItems: 'center', justifyContent: 'space-between' }}>
<CheckBox
disabled={false}
value={checked}
onValueChange={(newValue) => { setIschecked(newValue) }}
/>
<Text>{b.text} </Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={{ fontSize: 10, fontWeight: 'bold', color: COLORS.darkgray }}>
{" USD " + b.price}
</Text>
</View>
</View>
)
})}
我发现了一个与我的问题完全相同的问题 this one 但不幸的是,这对我不起作用
感谢并提前
【问题讨论】:
-
如果你有一个项目数组,你不能只使用一个标志来存储所有它们的状态(除非你想要单选框),你需要有一个选中的项目数组,所以它'将是
value={checked[b.id]}和const newArray = checked.slice(), newArray[b.id]=newValue;setIschecked(newArray) -
@NadiaChibrikova 我收到了这个错误
ypeError: checked.slice is not a function. (In 'checked.slice()', 'checked.slice' is undefined)。我做了什么我通过newValue来执行以下操作const newArray = checked.slice(); newArray[b.id]=newValue;setIschecked(newArray) -
在可以使用状态时需要将checked作为数组发起
-
所以应该是这样的吧?
const [checked, setIschecked] = useState([]) -
是的,应该这样做
标签: reactjs react-native checkbox react-hooks