繁体   English   中英

React Native 中的图像更改 onPress

[英]Image change onPress in React native

import React, { useState } from 'react'
import { Text, View, StyleSheet, Image, TouchableOpacity, Platform } from 'react-native'
import HeaderComponent from '../../components/HeaderComponent'
import NavigationFooter from '../../components/NavigationFooter'

const ReportScreen = () => {

    return (
        <View style={styles.viewcontainer}>
            <HeaderComponent title="Taak" />

            <Text style={styles.subtext}>Selecteer het taak type</Text>

我想改变形象onPressTouchableOpacity下面,但我不知道该怎么做,与useState

            <TouchableOpacity>
                    <View style={styles.graycontainer}>
                        <Image style={styles.grayimg} source={require('../../../assets/report/gray.png')} />
                        <Text style={styles.graytext}>Grijs</Text>)
                    </View>
            </TouchableOpacity>
            

        </View>        
    
    )
}

你可以像这样使用 Pressable:

import { View, Image, StyleSheet, Pressable } from 'react-native';

import imagesOn from '../../../assets/report/grayOn.png'
import imagesOff from '../../../assets/report/grayOFF.png'
let [flag, setflag] = React.useState(true);

let changeImage = () => setFlag(previousState => !previousState);

let imagePath= flag ? imagesOn : imagesOff
------
-----
<Pressable onPress={ () => changeImage() }>
            <View style={styles.graycontainer}>
                <Image style={styles.grayimg} source={imagePath} />
                <Text style={styles.graytext}>Grijs</Text>)
            </View>
    </Pressable>
import React, { useState } from 'react'
import { Text, View, StyleSheet, Image, TouchableOpacity, Platform } from 'react-native'
import HeaderComponent from '../../components/HeaderComponent'
import NavigationFooter from '../../components/NavigationFooter'

const ReportScreen = () => {
  const img = require("../../../assets/report/gray.png")
  const [imageAsset, setImageAsset] = useState(img)

  const handleImageChange = () => {
    const newImg = require("../path/to/your/image")
    setImageAsset(newImg)
  }
  return (
    <View style={styles.viewcontainer}>
      <HeaderComponent title="Taak" />

      <Text style={styles.subtext}>Selecteer het taak type</Text>
      <TouchableOpacity onPress={handleImageChange}>
        <View style={styles.graycontainer}>
          <Image
            style={styles.grayimg}
            source={imageAsset}
          />
          <Text style={styles.graytext}>Grijs</Text>
        </View>
      </TouchableOpacity>
    </View>
  )
}

将初始图像保存在上面的 useState 中,并使用您想要的图像更改 onPress 处理程序中的状态,然后将其传递给 TouchableOpacity。 确保在 Image 组件上正确设置了样式,尤其是宽度和高度,否则将不会显示图像。

顺便提一下,在 RN 的更高版本中,TouchableOpacity 可能会被弃用。 考虑使用 Pressable 代替。

暂无
暂无

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

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