reactjs 在React Native中单击时更改图像

zwghvu4y  于 2023-01-04  发布在  React
关注(0)|答案(1)|浏览(141)

我正在尝试创建一个应用程序,当点击图像时,它会变成许多图像中的一个。我使用了可触摸的不透明度,可以让图像在点击时显示警报。我只是不能让它变成文件中许多其他图像中的一个。
下面是我目前为止编写的所有代码:

import React from 'react';

import { Component, Stylesheet, useState, TouchableOpacity, Button, View, Text, Image, ScrollView, TextInput, Alert } from 'react-native';

// main part of the app
const App = () => {
  

  var array = [require("./cards/card.png"), require("./cards/card2.png")]
  var x = 0
  

  //onclick function
  const handlePress = () => {
    //some logic
    alert("help")
    x+=1
  }
  
  // what shows up on the app
  return (

    <ScrollView>

      <View>
          <Text>{array[x]}</Text>
          <Text>{x}</Text>
          <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          
          <TouchableOpacity
            onPress={(handlePress)}
          >

            <Image
              style={{ 
                width: 300,
                height: 300,
              }}
              resizeMode="contain"
              source={
                array[x]
              }
            />

          </TouchableOpacity>

          </View>

      </View>

    </ScrollView>
    
  );
}

export default App;

我希望卡片更改为的其他图像位于卡片文件夹中。如何使其动态化并将其更改为文件夹中的任何其他卡片?

yqkkidmi

yqkkidmi1#

为了改变图像或任何信息在屏幕上已经挂载,React必须重新渲染屏幕,并把正确的信息,你想要的.
要实现这一点,应使用React状态https://reactnative.dev/docs/state
您的代码可能如下所示:

import React from 'react';

import { Component, Stylesheet, useState, TouchableOpacity, Button, View, Text, Image, ScrollView, TextInput, Alert } from 'react-native';

// main part of the app
const App = () => {
  
  const [card, setCard] = useState(0); //initial state

  var array = [
    "./cards/card.png", 
    "./cards/card2.png"
  ]
  

  //onclick function
  const handlePress = () => {
    //some logic
    //set card state to the next index
    setCard( current => current + 1);

    //so everytime you click function the state will change and this re-render your component with the new data.
  }
  
  // what shows up on the app
  return (

    <ScrollView>

      <View>
          <Text>{array[card]}</Text>
          <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          
          <TouchableOpacity
            onPress={(handlePress)}
          >

            <Image
              style={{ 
                width: 300,
                height: 300,
              }}
              resizeMode="contain"
              source={ require(array[card]) }
            />

          </TouchableOpacity>

          </View>

      </View>

    </ScrollView>
    
  );
}

export default App;

相关问题