Snack
你可以使用TouchableWithoutFeedback处理onPress或者如果你不关心原生透明flash,你可以使用TouchableOpacity
这里我使用 useState 来定义列表中的哪个项目被选中,并根据样式将颜色设置为红色。
import React, { useState } from "react"
import {
View,
FlatList,
Text,
TouchableWithoutFeedback,
StyleSheet,
} from "react-native"
const data = [{ title: "blach" }, { title: "lol" }]
export default function App() {
const [selectedItem, toggleSelected] = useState(null)
const renderItem = ({ item, index }) => {
const toggleItem = (index) => {
console.log(index)
toggleSelected(index)
}
const isSelected = selectedItem === index
return (
<TouchableWithoutFeedback onPress={(ev) => toggleItem(index)}>
<View style={{ backgroundColor: "blue", marginBottom: 2 }}>
<Text
style={
!isSelected
? styles.text
: { ...styles.text, backgroundColor: "rgba(255,0,0,1)" }
}
>
{item.title}
</Text>
</View>
</TouchableWithoutFeedback>
)
}
return (
<View style={{ paddingTop: 20 }}>
<View style={{ padding: 10 }}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item, index) => `${item.title}_${index}`}
/>
</View>
</View>
)
}
const styles = StyleSheet.create({
text: {
padding: 20,
flex: 1,
backgroundColor: "#AB9F9F",
fontSize: 30,
color: "black",
borderWidth: 2,
borderColor: "black",
},
})