首页 > 解决方案 > 如何在另一个组件内设置背景颜色?反应原生

问题描述

我想做这个:

在此处输入图像描述

如您所见,它是一个元素列表,每个元素都有自己的背景颜色,我想当我选择其中一个时在它们上方创建一个透明的背景突出显示?有了这个,我仍然可以看到笔记的原始背景颜色和这个透明的高光,我有这个:

<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 的文本组件,问题是如果我添加不透明度,它们将结合创建紫色,但如果我不这样做,只有将显示背景颜色红色

标签: javascriptreact-native

解决方案


小吃

你可以使用TouchableWithoutFeedbackonPress 来处理,或者如果你不关心原生透明闪光灯,你可以使用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",
  },
})

推荐阅读