【问题标题】:Require non-static image in React Native在 React Native 中需要非静态图像
【发布时间】:2020-11-28 11:00:33
【问题描述】:

我的 React Native 应用程序中有一个包含图像的特殊文件夹。这些图片的路径存储在作为道具传递给卡片组件的特殊对象中。所以,我不能使用require,因为它只使用静态路径字符串。如何使用从我的道具加载这些图像?这是我的尝试:

import React from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  StyleSheet
} from 'react-native';
import EmptyImage from '../data/images/empty-image.jpg';

class Card extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {

    const { myObject } = this.props;

    return (
    <View>
        <Image 
           source={
               myObject.imagesNames[0] ?
                  require(`../data/images/${myObject.imagesNames[0]}`)
               :
                  EmptyImage
            }  
         /> 
    </View>
    );
  }
}

export default Card;

【问题讨论】:

    标签: javascript image react-native require


    【解决方案1】:

    由于您的图像是本地图像,因此最好通过要求以下图像来创建 json 对象

    images={
      image1:require('path'),
      image2:require('path2'),
    };
    

    你可以像下面这样设置网址

    <Image source={
                   myObject.imagesNames[0] ?images[imagesNames[0]]:EmptyImage
                }  
             /> 
    

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 1970-01-01
      • 2016-06-22
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多