【问题标题】:Displaying random image from array in React Native在 React Native 中显示来自数组的随机图像
【发布时间】:2020-09-12 12:36:34
【问题描述】:

我对 React 和 React Native 还是很陌生,当按下 TouchableOpacity 并调用我的函数 displayRandomImage() 时,我需要一些帮助来显示数组中的随机图像。

我得到的错误是

ReferenceError:找不到变量:imgIndex

我尝试将数组索引手动设置为 0 或 1 source={this.images[0].link},效果很好,但我不知道为什么 imgIndex 不被识别为随机数。

如果您能帮我解决这个问题,我会非常高兴。请在下面找到组件代码。

export default class A extends React.Component {
    constructor () { 
        super();
        this.state = {
            showImageApa: false,
            imgIndex: null,

        };
      }


images = [{link:require('./assets/apa.png')},{link:require('./assets/bil.png')} ];



     displayRandomImage = () => {
      this.setState({
        imgIndex: Math.floor(Math.random() * 3)
      });

        this.setState({showImageApa: true});

        setTimeout(() => {
          this.setState({showImageApa: false});
          }, 1000);
      };



  render() {
    return (

    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <LinearGradient
            colors={['rgba(25,172,255,0.8)', 'cyan']}
            style={{
              position: 'absolute',
              left: 0,
              right: 0,
              top: 0,
              height: 800,
            }}
          />
          <Text style={styles.buttonTextTop}>MAX ABC</Text>
          <Text style={styles.buttonTextVersion}>ver 0.2</Text>

          {this.state.showImageApa &&
        <View>
        <Image 
        style={styles.img}
        source={this.images[0].link}/> 
        <Text style={styles.buttonText}>Apa</Text>

        </View>}

              <TouchableOpacity
                  style={[styles.button]}
                onPress={() => {this.displayRandomImage();}}>
            <Text style={styles.buttonText}>A</Text>
              </TouchableOpacity>


    </View>
    );
  }
} 

【问题讨论】:

  • 当状态改变时响应更新,所以使用 this.images[this.state.imgIndex].link
  • 试过了,效果很好。我以为我之前就尝试过这个,但我想我当时做错了什么。不过,非常感谢您的帮助!

标签: arrays image react-native random display


【解决方案1】:

如果 images 数组中只有两个对象,则可以通过引用 images[0] 或 images[1] 来确定它们的位置。但是,当您使用 Math.floor(Math.random * 3) 函数时,它会返回值 [0, 2],并且没有在图像 [2] 上定义对象。因此,解决方案是将 Math.floor(Math.random * 3) 更改为 Math.floor(Math.random * 2) 以便返回的值是0 或 1 来引用正确的索引。

祝你的 React Native 之旅好运!

【讨论】:

  • 您好,感谢您的回答。是的,我现在意识到了这个错误,当然应该是 2。我改变了它并将 this.images[this.state.imgIndex].link 添加到 onPress 事件中,现在它可以工作了!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 2021-12-19
  • 2019-04-11
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
相关资源
最近更新 更多