无法在Node.js内使用变量名

时间:2018-11-29 15:06:25

标签: node.js react-native require

我想将图像导入我的本地本机应用程序。

render() {

    console.log(this.props.image);   //   this logs '../../images/avatartest.jpg' every time

    let test = require (this.props.image!);   //    bang is required because of interface
    return (
        <ImageBackground
            source={test}
        >
        </ImageBackground>
    );
}

运行此代码会产生此错误:

enter image description here

没有办法接受带有字符串的变量名吗?

2 个答案:

答案 0 :(得分:1)

所有需求都必须是可静态分析的。这意味着您不能在require中使用变量。

您可以在应用程序中手动捆绑图像,并在变量起作用的地方使用。

<Image source={{ uri: this.props.image }} />

答案 1 :(得分:0)

您要在此处执行的操作是动态导入不支持的图像,最好的方法是事先要求图像并传递所需的值作为道具。假设您组件的父组件是ImageView

export default const images = {
   img1:require('IMAGE_URL')
}

//import this in the your view and use it as the prop value 
<ImageView image={images.img1}></ImageView>

以上方法将确保打包程序可以找到图像。