我是 React-Native 的新手,我在识别 React-Native 的平面列表中按下哪个按钮时遇到问题。我可以让它们全部改变,但我想让它们单独改变。我已经在每个元素中放置了一个名为 num 的标识符,但我不知道如何识别每个按钮。我的想法是让每个按钮都有一个 id (num),并在 onPress 属性中识别按下了哪个按钮并更改其颜色。另外,我不知道是否需要为每个按钮制作不同的 CSS,或者是否可以从 main 更改它们。
提前致谢。
PD:抱歉我的英语不好,我来自智利
主要:
const main = () => {
const [pressedButton, setPressedButton] = useState("#1e1e1e")
return (
<View style = {styles.container}>
<View style = {styles.nav}>
<View style={styles.nav_container}>
<Text style = {styles.title_main}>Habits</Text>
</View>
<View style = {styles.divider_main} />
</View>
<ScrollView style = {styles.body_main}>
<FlatList
data = {[
{key: "Habit", desc: "30 Minutes a Day", num: 0},
{key: "Habit", desc: "30 Minutes a Day", num: 1},
{key: "Habit", desc: "30 Minutes a Day", num: 2},
{key: "Habit", desc: "30 Minutes a Day", num: 3},
]}
renderItem = {({item}) =>
<View style = {styles.list_item}>
<Text style = {styles.list_item_text}>{item.key}</Text>
<Text style = {styles.list_item_desc}>{item.desc}</Text>
<TouchableWithoutFeedback
onPress = {() => {
pressedButton == "#1e1e1e" ? setPressedButton("#9747FF") : setPressedButton("#1e1e1e")
}}>
<View style = {[styles.check_mark, {backgroundColor: pressedButton}]}>
<Image source = {require("./assets/black-check.png")} style = {styles.check_mark_img}/>
</View>
</TouchableWithoutFeedback>
</View>}
style = {styles.list_main}
/>
</ScrollView>
<View style = {styles.add_habit}>
<View style = {styles.add_habit_vert}></View>
<View style = {styles.add_habit_hor}></View>
</View>
</View>
);
};
CSS:
check_mark: {
width: 50,
height: 50,
borderRadius: 25,
borderColor: "#9747FF",
borderWidth: 3,
backgroundColor: "#1e1e1e",
position: "absolute",
right: 20,
alignItems: "center",
justifyContent: "center",
},
您可以在
renderItem
中使用索引。
使用
setPressedButtonIndex
将该索引保存在状态中,如果项目的索引等于 pressedButtonIndex
,则添加背景样式
const [pressedButtonIndex, setPressedButtonIndex] = useState(null)
renderItem = {({item, index}) =>
<View style = {styles.list_item}>
<Text style = {styles.list_item_text}>{item.key}</Text>
<Text style = {styles.list_item_desc}>{item.desc}</Text>
<TouchableWithoutFeedback
onPress = {() => {
setPressedButtonIndex(index)
}}>
<View style = {[styles.check_mark, index === pressedButtonIndex ? {backgroundColor: "#1e1e1e"} : {}]}>
<Image source = {require("./assets/black-check.png")} style = {styles.check_mark_img}/>
</View>
</TouchableWithoutFeedback>
</View>}
style = {styles.list_main}