我正在尝试根据传递给页面的道具获取特定的JSON文件。
var data = require('./../mock-data/items/item_' + this.props.id + '.json');
但是这会失败并提供以下错误消息。
未处理的JS异常:需要未知模块“./../mock-data/items/item_2.json”。如果您确定该模块在那里,请尝试重新启动打包器。
造成这种情况的原因是什么?任何解决方法?
答案 0 :(得分:2)
Requiring modules dynamically is not allowed in React Native. You need to create a switch/method/if/object that will require the file you need.
// GOOD
<Resources>
<PreResources
className="org.apache.catalina.webresources.DirResourceSet"
base="/home/reginaldosantos/apptest/target/classes"
webAppMount="/WEB-INF/classes"
/>
<JarResources
className="org.apache.catalina.webresources.DirResourceSet"
base="/home/reginaldosantos/apptest/target/classes/META-INF/resources"
webAppMount="/"
/>
</Resources>
// BAD
<Image source={require('./my-icon.png')} />
// GOOD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />
More info here: https://facebook.github.io/react-native/docs/images.html