require() 必须有一个字符串文字参数 React Native [英] require() must have a single string literal argument React Native

查看:58
本文介绍了require() 必须有一个字符串文字参数 React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个组件,如果它被分配了直接字符串值(someImage.png"),它就可以正常工作,但是如果我尝试通过将图像名称存储在局部变量中来分配它,则会出现此异常require() 必须有一个字符串文字参数"这条线工作正常

I've component in my application which works fine if it is assigned direct string value("someImage.png"), but if I try to assign it by storing image name in a local variable it gives this exception "require() must have a single string literal argument" This line works fine

<ImageBackground source={require("./Resources/bg/imageone.png")} resizeMode='cover' style={customStyles.backdrop}>

在这种情况下出现问题

let imageName = "./Resources/bg/imageone.png";          
<ImageBackground id="123" source={require(imageName)} resizeMode='cover' style={customStyles.backdrop}>

我还发现此处报告了同样的问题,但还没有人回答这个问题.你能帮我看看吗?

I also found same issue reported here, but no one has answered that yet. Can you help me out here?

推荐答案

这个动态图像的例子还可以展示如何正确地为一个变量分配图像源值.建议将整个 require 分配到一个变量中,而不仅仅是它的值.

This example of dynamic images can also show how to correctly assign a variable with the image source value. The recommendation is to assign the whole require in a variable, instead of just its value.

// GOOD
<Image source={require('./my-icon.png')} />;

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;

// GOOD
var icon = this.props.active
  ? require('./my-icon-active.png')
  : require('./my-icon-inactive.png');
<Image source={icon} />;

https://facebook.github.io/react-native/docs/图片.html

希望能帮到你

这篇关于require() 必须有一个字符串文字参数 React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆