React Native: how to use require(path) with dynamic urls?

こ雲淡風輕ζ 提交于 2019-12-01 11:57:00

问题


I want to use WebView to show some html content

here is an example:

return (
            <WebView
                    style={styles.container}
                    source={source}
                    scalesPageToFit={Boolean(true)}
                    onNavigationStateChange={this._onNavigationStateChange} />
    )

and for the source variable I need to have two different values:

1) for android platform I need to use something like this:

source = {uri: `file:///android_asset/contents/${languageId}text.html`}

2) for ios I need to use smth. like this:

source = require(`../srv/localization/contents/${languageId}text.html`)

For android it works well, but for ios it doesn't work. And this url works fine for iOS also

require(`../srv/localization/contents/entext.html`)

As I understand that is because of dynamic url (${languageId}text.html)

The question is how to use dynamic urls for iOS?


回答1:


As you find out, you can't have dynamic url for require. That's because require get the source at the app start regardless it's place in the code. You shuld require all of the {languageId}text.html and pass the required variable to the source:

var language = {
   en: require(`../srv/localization/contents/entext.html`)
   ...
}

and use it as below:

source = require(language[en])


来源:https://stackoverflow.com/questions/43516269/react-native-how-to-use-requirepath-with-dynamic-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!