React Native:require()with Dynamic String?

Jak*_*san 24 javascript require ecmascript-6 reactjs react-native

我已经阅读了几篇关于人们在使用React Native require()时遇到的问题以及尝试需要动态资源时的功能的帖子,例如:

动态(失败):

urlName = "sampleData.json";
data = require('../' + urlName);
Run Code Online (Sandbox Code Playgroud)

与静态(成功):

data = require('../sampleData.json');
Run Code Online (Sandbox Code Playgroud)

我已经阅读了一些线程,这是React Native中的一个错误,而在其他线程中,这是一个功能.

是否有一种新方法需要函数内的动态资源?

相关帖子(在React时间都相当老):

小智 16

Here is my solution.

Setup

File structure:

app  
  |--src
    |--assets
      |--images
        |--logos
          |--small_kl_logo.png
          |--small_a1_logo.png
          |--small_kc_logo.png
          |--small_nv_logo.png
          |--small_other_logo.png

        |--index.js
    |--SearchableList.js
Run Code Online (Sandbox Code Playgroud)

In index.js, I have this:

const images = {
  logos: {
    kl: require('./logos/small_kl_logo.png'),
    a1: require('./logos/small_a1_logo.png'),
    kc: require('./logos/small_kc_logo.png'),
    nv: require('./logos/small_nv_logo.png'),
    other: require('./logos/small_other_logo.png'),
  }
};

export default images;
Run Code Online (Sandbox Code Playgroud)

In my SearchableList.js component, I then imported the Images component like this:

import Images from './assets/images';
Run Code Online (Sandbox Code Playgroud)

I then created a new function imageSelect in my component:

imageSelect = network => {
  if (network === null) {
    return Images.logos.other;
  }

  const networkArray = {
    'KL': Images.logos.kl,
    'A1': Images.logos.a1,
    'KC': Images.logos.kc,
    'NV': Images.logos.nv,
    'Other': Images.logos.other,
  };

  return networkArray[network];
};
Run Code Online (Sandbox Code Playgroud)

Then in my components render function I call this new imageSelect function to dynamically assign the desired Image based on the value in the this.state.network:

render() {
  <Image source={this.imageSelect(this.state.network)} />
}
Run Code Online (Sandbox Code Playgroud)

The value passed into the imageSelect function could be any dynamic string. I just chose to have it set in the state first and then passed in.

I hope this answer helps. :)


kle*_*ndi 14

正如我所听到的,反应的require()只使用静态URL不变量,这意味着你必须做的require('/path/file'),看看这个GitHub上的问题这一个更多的替代解决方案,也有一些其他的方式来做到这一点!例如

const images = {
profile: {
    profile: require('./profile/profile.png'),
    comments: require('./profile/comments.png'),
},
   image1: require('./image1.jpg'),
   image2: require('./image2.jpg'),
};

export default images;
Run Code Online (Sandbox Code Playgroud)

然后

import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}
Run Code Online (Sandbox Code Playgroud)

从这个答案


小智 -1

您是否使用像 webpack 这样的模块捆绑器?

如果是这样,你可以尝试require.ensure()

请参阅: https: //webpack.js.org/guides/code-splitting/#dynamic-imports