[英]How to set the overall background color behind the view in React-Native
[英]How to set background color inside another component? REACT-NATIVE
我想做这个:
如您所见,它是一个元素列表,每个元素都有自己的背景颜色,我希望当我选择其中一个元素时,在它们上方创建一个透明的背景高光? 有了这个,我仍然可以看到笔记的原始背景颜色和这个透明的高光,我有这个:
<View style = {{backgroundColor: "blue"}}>
<Text style = {{padding: 20,
flex: 1, backgroundColor: "red", opacity: 0.5, fontSize: 30, color: "black"}}>{item.title}
</Text>
</View>
如您所见,有一个背景色为蓝色的视图组件和一个背景色为红色且不透明度为 0.5 的文本组件,问题是如果我添加不透明度,它们将结合创建紫色,但如果我不这样做,则只有将显示背景颜色为红色
你可以使用TouchableWithoutFeedback
来处理 onPress 或者如果你不关心原生透明 flash,你可以使用TouchableOpacity
这里我使用 useState 来定义列表中的哪个 item 被选中,并根据样式设置颜色为 Red。
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",
},
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.