在 react-native 中需要一个包含 var 的 var

Require a var that contains a var in react-native

我正在使用 React Native,我正在为我的按钮创建一个 Class。该按钮包含一个图像。在这里,我已经在我的视图中减速了我的按钮。

var imageUrl = { //this is a var from a JSON object there could be more than 20 different images 
          normal: "../assets/images/emoticons/1.png",
          selected: "../assets/images/emoticons/1-selected.png"
}

<Button key={index}
        selected={true}
        onPress={onSelect}
        imageUrl={imageUrl} />

在 'Button' Class 中,我创建了一个 _renderImage 函数来设置按钮中的图像。

_renderImage(imageUrl){
    let image = (selected === true) ? require(imageUrl.normal) : require(imageUrl.selected); //get the right image url

    console.log('../assets/images/emoticons/1.png'); //logs  '../assets/images/emoticons/1.png'
    console.log(typeof('../assets/images/emoticons/1.png')); //logs string
    console.log(image); //logs '../assets/images/emoticons/1.png'
    console.log(typeof(image)); //logs string

    return (
      <Image source={require(image)} />
    );

}

这个函数报错。在此处的屏幕截图中,您可以看到错误。

当我手动设置时 <Image source= require('../assets/images/emoticons/1.png)} /> 它会渲染图像。所以图像存在于这个位置。

像这样的类似问题并不能解决我的问题:

根据文档,我认为目前这在 React Native 中是不可能的:

Note that in order for this to work, the image name in require has to be known statically.

来自https://facebook.github.io/react-native/docs/images.html