在反应原生中获取图像时,require()不使用插值字符串

时间:2017-02-28 09:52:36

标签: javascript react-native

我在React Native中使用Image组件作为背景,并且我正在为源prop提供如下图像,这是有效的。

const ImageWrapper = (props) => {
      return (
        <Image source={require('../../../images/testingImages/cells.png')} style={styles.imageView}>
          {props.children}
        </Image>
      );
    };

但是,我想提供一个带有插值字符串的require,其中包含由prop提供的图像名称,如下所示:

require(`../../../images/testingImages/${props.imgURL}`)

但每当我这样做时(即使我在不​​使用ES6的情况下将字符串创建为单独的变量并将其传递给require)。我收到了错误 -

  

“未知的命名模块'../../../ images / testingImages / cells.png'”。

没有使用require需要获取图像吗?因为我希望能够将图像url作为道具传递,以便在我想要更改背景时可以重复使用该组件。

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:1)

希望其他人可以为您的确切问题提供解决方案,因为我遇到了同样的问题,但我的解决方法是将source的整个值作为道具传递。我将其作为我的场景中列表中每个地图的某个键的值,因此对我来说足够干净。但这可能只是将问题提升到你的水平。

答案 1 :(得分:0)

我不确定它是否能解决您的问题,但如果您的图片可通过网络获得,则可以使用您的基本网址创建图片的网址,并将该网址直接作为来源使用。

var fileName = "trolltunga.jpg";
var imagesBaseUrl = "https://www.w3schools.com/css/";
var image = imagesBaseUrl+fileName;
const imageURL = {url:image}

class App extends React.Component {
render() {
 return (
  <Image source={imageURL} style={styles.imageView}>
 </Image>
  );
 }
}

在此处进行演示检查https://rnplay.org/apps/hEYzcA

答案 2 :(得分:0)

这是我如何专门解决这个问题,不是一个完美的答案,而是为了我的目的。我认为在组件加载时调用require,因此字符串没有机会进行插值以便传递。因此,我在图像包装器的父组件中导入相关图像:

import jungle from '../../images/jungle.jpg';

然后作为道具传递给Image Wrapper

<ImageWrapper image={jungle} />

然后将此道具传递给图像源组件:

<Image source={this.props.image} style={styles.imageView}>
          { this.props.children }
</Image>

答案 3 :(得分:0)

首先创建一个需要图像的文件-必须以这种方式加载React本机图像。

assets / index.js

export const leftChevron = require('./left-chevron.png'); 
export const rightChevron = require('./right-chevron.png'); 
export const circle = require('./oval-bottom-right.png'); 
export const homeandgarden = require('./homeAndGarden.png');

现在导入所有资产

App.js

import * as All  from '../../assets';

您现在可以将图像用作插值,其中imageValue与命名的本地文件相同:

<Image style={styles.image} source={All[`${imageValue}`]}></Image>