javascript - 如何在另一个组件内设置背景颜色?反应原生
问题描述
我想做这个:
如您所见,它是一个元素列表,每个元素都有自己的背景颜色,我想当我选择其中一个时在它们上方创建一个透明的背景突出显示?有了这个,我仍然可以看到笔记的原始背景颜色和这个透明的高光,我有这个:
<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 来处理,或者如果你不关心原生透明闪光灯,你可以使用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",
},
})
推荐阅读
- python - 我正在尝试训练我的 X_train 和 y_train 但存在一些数组维度问题
- algorithm - 如何找到从所有可能的子数组中选择的最小元素和次小元素的最大和
- javascript - bit.dev 相当于分叉一个 repo 并提交一个 PR 是什么?
- reactjs - 反应性能优化
- r - 谷歌地形视图和卫星视图在 R 中使用 GGMAP 使用 Zoom 和 ggsn :: scalebar
- c++ - clion中llvm c++ api的语法高亮
- centos7 - 无法在 Centos7 中启动 node_exporter.service 以进行 Prometheus 监控 - 无法执行操作:错误消息
- python - 将十六进制格式转换为字符串
- css - 如何在 bootstap-vue 切换按钮中更改背景颜色
- android - 如何在 API 完成时暂停 Kotlin 中的执行