首页 > 解决方案 > React Native 中的图像更改 onPress

问题描述

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>        
    
    )
}

标签: javascriptreactjsreact-nativereact-hooksmobile-development

解决方案


你可以像这样使用 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>

推荐阅读