如何实现具有复选框行为的列表



我有一个项目,它有一个类别列表

var category = [
{
isSelected: false,
title: "Meditation",
},
{
isSelected: false,
title: "Live Video",
},

]

这将显示Touchableopacity的列表,当我单击其中一个时,它将更改颜色,如果我再次单击,它将返回到原始全色

下面是它工作的链接(https://snack.expo.dev/S1v5KIJvi)下面我用代码注释来解释代码。

import * as React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';

/* 
Checkbox component
*/
const CheckBox = ({boxes,index,onPress})=>{
return (
<TouchableOpacity 
onPress={onPress.bind(this,index)}
style={{
margin:10,
width:50,
height:50,
backgroundColor:boxes[index].isSelected?"green":"black"
}
}>
</TouchableOpacity>
)
}
export default function App() {
/* 
Data to keep track of your boxes
*/
const [boxes,setBoxes] = React.useState([
{
isSelected: false,
title: "Meditation",
},
{
isSelected: false,
title: "Live Video",
}]);

/*
Changes isSelected to true based on the index of the box
*/
const onPress = (index)=>{
const newBoxes = [...boxes];
newBoxes[index].isSelected = !(newBoxes[index].isSelected)
setBoxes(newBoxes)
}


return (
<View style={{
flex:1,
justifyContent:"center",
alignItems:"center",
}}>
{
boxes.map((_,index)=>{
return <CheckBox onPress={onPress} boxes={boxes}  index={index} key={index.toString()}/>
})
}
</View>
);
}
export default function App() {
const [category, setCategory] = useState([
{
isSelected: false,
title: "Meditation",
},
{
isSelected: false,
title: "Live Video",
},
])

const handleItemPress = index => {
// alert(index)
const temp = category
temp[index].isSelected = !category[index].isSelected
setCategory(temp)
}
const renderItem = ({ item, index }) => {
return (
<TouchableOpacity
onPress={() => handleItemPress(index)}
style={{
backgroundColor: item.isSelected == true ? 'tan' : null,
height: 65,
width: '90%',
marginLeft: '5%',
borderRadius: 10,
borderColor: 'black',
marginBottom: 10,
borderWidth: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>
{item.title}
</Text>
</TouchableOpacity>
)
}
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<FlatList
data={category}
keyExtractor={(item, index) => String(index)}
renderItem={renderItem}
/>
</View>
</SafeAreaView>
)
}

票据

如果您在onPress之后没有从值中得到更新从falsetrue中选择e.g.onClick

I mean you get the updated value in logger but changes may not reflect in UI

然后添加一个状态

const [refresh, setRefresh] = useState()

并在handleItemPress()方法中更新该状态值

const handleItemPress = index => {
const temp = category
temp[index].isSelected = !category[index].isSelected
setCategory(temp)
setRefresh(Math.random())
}

就像我在做这个例子时面临这个问题一样,这就是我写这个Notes 的原因

最新更新