Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从react native中的阵列中随机选择图像_Javascript_Arrays_Reactjs_React Native - Fatal编程技术网

Javascript 从react native中的阵列中随机选择图像

Javascript 从react native中的阵列中随机选择图像,javascript,arrays,reactjs,react-native,Javascript,Arrays,Reactjs,React Native,我试图从包含图像的数组中随机选择一个图像,但我一直得到提供给图像的无效道具源。我希望每次用户在应用程序中打开屏幕时,页面都会显示不同的随机图像。下面是我的示例代码 import image2 from '../../../../assets/images/image2.png'; import image3 from '../../../../assets/images/image3.png'; import image4 from '../../../../assets/images/imag

我试图从包含图像的数组中随机选择一个图像,但我一直得到提供给图像的无效道具源。我希望每次用户在应用程序中打开屏幕时,页面都会显示不同的随机图像。下面是我的示例代码

import image2 from '../../../../assets/images/image2.png';
import image3 from '../../../../assets/images/image3.png';
import image4 from '../../../../assets/images/image4.png';
import image6 from '../../../../assets/images/image6.png';

const images= [
  image1,
  image2,
  image3,
  image4,
  image6,
  ];

  componentDidMount() {
    this.changeImage();
  }

  changeImage = () => {
    const randomNumber = Math.floor(Math.random() * images.length);
    this.setState({
      currentImageIndex: randomNumber
    });
  }

          <Image
            source={{ uri: images[this.state.currentImageIndex] }}
            style={styles.imageStyle}
          />


从“../../../../assets/images/image2.png”导入image2;
从“../../../../assets/images/image3.png”导入image3;
从“../../../../assets/images/image4.png”导入image4;
从“../../../../assets/images/image6.png”导入image6;
常量图像=[
图1,
图2,
图3,
图4,
图6,
];
componentDidMount(){
这个.changeImage();
}
changeImage=()=>{
const randomNumber=Math.floor(Math.random()*images.length);
这是我的国家({
currentImageIndex:随机数
});
}

在react native中,从相对路径导入图像时,必须将其直接传递给
图像
组件的源道具

以下是它应该如何工作:

  <Image
    source={images[this.state.currentImageIndex]}
    style={styles.imageStyle}
  />


react native
Image
组件(如果您正在使用该组件)需要
source
,而不是
src
。抱歉。。。这是我在尝试使用其他内容时遇到的一个错误,因为源代码抛出了相同的错误。我已经在上面的问题中修改了它。