【问题标题】:How do I display a random image retrieved from an array in react native如何在本机反应中显示从数组中检索到的随机图像
【发布时间】:2020-05-01 21:18:58
【问题描述】:

我正在尝试随机显示本地文件中的图像,这些图像已存储在 Card 组件中的数组中,然后在应用程序(应用程序的根目录)中呈现。

这是包含同一目录中图像数组的图像文件。

const woolyImages = [
  require('images/wooly1'),
  require('images/wooly2'),
  require('images/wooly3'),
  require('images/wooly4'),
  require('images/wooly5'),
];

export default woolyImages;

这是 Card 组件,我尝试从数组中选择一个随机图像并通过“source”使用 Image 组件显示它。

import React from 'react';
import {Image, View, StyleSheet} from 'react-native';
import woolyImages from '../images/Images';

function Card() {
  const randomImage =
    woolyImages[Math.floor(Math.random() * woolyImages.length)];
  console.log(randomImage);

  return (
    <View style={styles.cardContainer}>
      <Image source={randomImage} />
    </View>
  );
}

const styles = StyleSheet.create({
  cardContainer: {
    width: '50%',
    height: '35%',
    backgroundColor: 'pink',
  },
});

export default Card;

(我插入了粉红色背景,因此我可以确定它正在视图中呈现。确实如此。)

最后,这里是我渲染卡片的应用程序的根目录。

import React from 'react';
import {View, StyleSheet} from 'react-native';
import Header from './components/Header';
import Card from './components/Card';
import GenerateWoolyButton from './components/GenerateWoolyButton';

function App() {
  return (
    <View style={styles.container}>
      <Header />
      <Card />
      <GenerateWoolyButton style={styles.button} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'flex-start',
    alignItems: 'center',
    flex: 1,
  },
});

export default App;

我收到以下错误。

谁能告诉我如何在卡片组件中显示随机生成的图片并将其显示在我的应用程序的根目录中?谢谢。

【问题讨论】:

  • 当您的图像文件夹中没有图像或您设置了错误的路径时,会发生此错误。请检查您的终端以了解更多信息
  • 嗨@AnkushRishi。谢谢,我更新了路径,现在它们是正确的。我可以说出来,因为我的图像预览扩展程序适用于路径,但不幸的是图像仍然没有呈现。
  • 你还面临同样的错误吗?
  • @SDushan 否,但图像仍未在 Card 组件中呈现。没有错误,但什么也没发生

标签: react-native


【解决方案1】:

您需要在卡片组件的图像中添加widthheight 样式。比如,

<Image source={randomImage} style={{height: 200, width: 200}} />

希望这会对您有所帮助。如有疑问,请随意。

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 2019-04-27
    • 2023-03-05
    • 2018-09-29
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    相关资源
    最近更新 更多