必须有一个字符串文字参数React

必须有一个字符串文字参数React

本文介绍了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} />;

希望它帮助

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

08-24 06:03