简体   繁体   English

如何根据在 React Native 中按下哪个 Pressable 来显示图标?

[英]How to show icon depending on which Pressable is pressed in React Native?

I have a multiple Pressable component.我有多个 Pressable 组件。 How can I make it that when I clicked on the Motorcycle pressable, the check icon would be shown beside it and if on the Tricycle Pressable, the check icon would be shown beside it and the one on the Motorcycle icon will be gone.我怎样才能做到当我点击 Motorcycle pressable 时,复选图标会显示在它旁边,如果在 Tricycle Pressable 上,复选图标会显示在它旁边,而 Motorcycle 图标上的复选图标将会消失。

在此处输入图像描述

I have tried creating a state but it simultaneously set all icons in place.我试过创建一个 state 但它同时设置了所有图标。 Here is the code:这是代码:

  const [checkIcon, setCheckIcon] = useState(false)

<Pressable
            style={({ pressed }) => [{ opacity: pressed ? 0.4 : 1 }, styles.modalField]}
              onPress={() => setCheckIcon(true)}
            >
              <Image source={require("../assets/motorcycle.png")} style={styles.modalFieldImage} />
              <View style={styles.modalFieldVehicleNameContainer}>
                <Text style={styles.modalFieldText}>Motorcycle</Text>
                <Text style={styles.modalFieldTextDescription}>Cheapest option perfect for small-sized items</Text>
                <Text style={styles.modalFieldTextDescription}>Up to 20 kg</Text>
              </View>
              {
                checkIcon === true ? <Icon name="check" type="font-awesome-5" size={hp("3%")} color="#322C6A" style={styles.modalFieldIcon} /> : null
              }
            </Pressable>

            <Pressable
              style={({ pressed }) => [{ opacity: pressed ? 0.4 : 1 }, styles.modalField]}
              onPress={() => setCheckIcon(true)}
            >
              <Image source={require("../assets/tricycle.png")} style={styles.modalFieldImage} />
              <View style={styles.modalFieldVehicleNameContainer}>
                <Text style={styles.modalFieldText}>Tricycle</Text>
                <Text style={styles.modalFieldTextDescription}>Perfect for multiple medium-sized items</Text>
                <Text style={styles.modalFieldTextDescription}>Up to 70 kg</Text>
              </View>
              {
                checkIcon === true ? <Icon name="check" type="font-awesome-5" size={hp("3%")} color="#322C6A" style={styles.modalFieldIcon} /> : null
              }
            </Pressable>

            <Pressable
              style={({ pressed }) => [{ opacity: pressed ? 0.4 : 1 }, styles.modalField]}
              onPress={() => setCheckIcon(true)}
            >
              <Image source={require("../assets/sedan.png")} style={styles.modalFieldImage} />
              <View style={styles.modalFieldVehicleNameContainer}>
                <Text style={styles.modalFieldText}>Sedan Car</Text>
                <Text style={styles.modalFieldTextDescription}>Good for cakes and multiple small to medium-sized items</Text>
                <Text style={styles.modalFieldTextDescription}>Up to 200 kg</Text>
              </View>
              {
                checkIcon === true ? <Icon name="check" type="font-awesome-5" size={hp("3%")} color="#322C6A" style={styles.modalFieldIcon} /> : null
              }
            </Pressable>

Here is an simple example, using a index state to log down which item is selected by user.这是一个简单的例子,使用索引 state 来记录用户选择了哪个项目。

Since your list can be generated dynamically, so you may use an array to store all the parameters for rendering and use map() to render one by one.由于您的列表可以动态生成,因此您可以使用数组存储所有用于渲染的参数,并使用map()逐一渲染。

const [optionArray, setOptionArray] = useState([
    {
      title: "Motorcycle",
      desc1: "Cheapest option perfect for small-sized items",
      desc2: "Up to 20 kg",
      img: "../assets/motorcycle.png",
    },
    {
      title: "Tricycle",
      desc1: "Perfect for multiple medium-sized items",
      desc2: "Up to 70 kg",
      img: "../assets/tricycle.png"
    },
    {
      title: "Sedan Car",
      desc1: "Good for cakes and multiple small to medium-sized items",
      desc2: "Up to 200 kg",
      img: "../assets/sedan.png",
    }
  ]);
  const [selectedIndex, setSelectedIndex] = useState(-1);   //Nothing is selected with initial render

  const ListItem = ({option, index}) =>{
    return(
      <Pressable
        style={({ pressed }) => [{ opacity: pressed ? 0.4 : 1 }, styles.modalField]}
        onPress={() => setSelectedIndex(index)}
      >
        <Image source={option.img} style={styles.modalFieldImage} />
        <View style={styles.modalFieldVehicleNameContainer}>
          <Text style={styles.modalFieldText}>{option.title}</Text>
          <Text style={styles.modalFieldTextDescription}>{option.desc1}</Text>
          <Text style={styles.modalFieldTextDescription}>{option.desc2}</Text>
        </View>
        {
          index === selectedIndex && <Icon name="check" type="font-awesome-5" size={hp("3%")} color="#322C6A" style={styles.modalFieldIcon} />
        }
      </Pressable>
    )
  }

  return(
    <View>
      {
        optionArray.map((option, index) => 
          <ListItem option={option} index={index} />
        )
      }
    </View>
  )

Also answer by Hardik prajapati is another solution too. Hardik prajapati 的回答也是另一种解决方案。 That method will not affect the result when the data list is sorted in runtime.当数据列表在运行时排序时,该方法不会影响结果。 But large object modification will trigger re-render for components which may lead to performance issue in some case.但是较大的 object 修改将触发组件的重新渲染,这在某些情况下可能会导致性能问题。

Therefore, you can select different approach for your case.因此,您可以 select 针对您的情况采用不同的方法。

create Vehicle item array like vehicle:[ image:'put your imageUrl', name:'', description:'', clickStatus:true ]创建 Vehicle 项目数组,如vehicle:[ image:'put your imageUrl', name:'', description:'', clickStatus:true ]

then use map method to display all array item and when you click on any item update your array with clickStatus key pressable item true and other two item false and display Check Icon based on true or false然后使用 map 方法显示所有数组项,当您单击任何项时,使用clickStatus键可按下项 true 和其他两项 false 更新数组,并根据 true 或 false 显示检查图标

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为 React Native Pressable 配置波纹颜色? - How to configure the ripple color for a React Native Pressable? React Native - 如何使 TouchableOpacity 的一部分不可按下 - React Native - How to make portion of TouchableOpacity not pressable 在按下本机矢量图标时如何更改图标名称 - How to Change Icon name when pressed in react native vector icon React native 如何从 Pressable/Text 中获取价值 - React native How to get value from Pressable/Text React Native Web/Expo:如何在 Pressable 上模拟焦点可见? - React Native Web/Expo: How to emulate focus-visible on a Pressable? 如何在 TabNavigator 上显示图标以响应本机 - How to Show Icon on TabNavigator in react native 如何创建一个按钮,可按下或可触摸的不透明度,将我们重定向到使用本机反应的网站 - how to create a button, pressable or a touchable opacity that redirects us to a website using react native 如何为 React Native Web Pressable 组件正确添加 onHoverIn TS 类型? - How to correctly add the onHoverIn TS type for the React Native Web Pressable component? 如何在 React Native 中使用 svg 图像路径显示 svg 图标? - How to show an svg icon using svg image path in react native? 包裹在 Pressable 中的 react-native-swiper 在 iOS 上无法正常工作 - react-native-swiper wrapped in a Pressable not working properly on iOS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM