繁体   English   中英

如何在另一个组件内设置背景颜色? 反应本机

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM