我试图在JSON中循环,并为每个项目加载一个图片,但我得到一个语法错误。
const WizardContainer = props => {
ImagePathItems = [
{ path: '../../resources/svg/wizard-r.png', txtValue: "1" },
{ path: '../../resources/svg/wizard-c.png', txtValue: "2" },
{ path: '../../resources/svg/wizard-s.png', txtValue: "3" },
{ path: '../../resources/svg/wizard-d.png', txtValue: "4" }];
return (
<View style={styles.a}>
<View style={styles.b}>
<View style={styles.c}>
<FlatList
horizontal
data={ImagePathItems}
renderItem={({ item }) =>
<Image
style={styles.tinyLogo}
//source={require('../../resources/svg/wizard-d.png')}
source={require({ item.path })} //SYNTAX ERROR
/>
}
keyExtractor={item => item.txtValue}
/>
</View>
</View>
</View>
);
};
export default WizardContainer;
如果我删除前一行,加载图片就会很好。
更改 ImagePathItems
阵列和 Image
源于此
const WizardContainer = props => {
ImagePathItems = [
{ path: require('../../resources/svg/wizard-r.png'), txtValue: "1" },
{ path: require('../../resources/svg/wizard-c.png'), txtValue: "2" },
{ path: require('../../resources/svg/wizard-s.png'), txtValue: "3" },
{ path: require('../../resources/svg/wizard-d.png'), txtValue: "4" }];
return (
<View style={styles.a}>
<View style={styles.b}>
<View style={styles.c}>
<FlatList
horizontal
data={ImagePathItems}
renderItem={({ item }) =>
<Image
style={styles.tinyLogo}
source={item.path}
/>
}
keyExtractor={item => item.txtValue}
/>
</View>
</View>
</View>
);
};
export default WizardContainer;
你能不能试试把require放到数据对象中。
{path: require('../../resources/svg/wizard-r.png'), txtValue: 1}
然后在你的代码中,你可以直接引用为:
<Image source={(item.path)} />
这样可以吗?
你不能用 require
因为jsbundler是在构建时运行的,当名称是一个动态变量时,它无法确定要捆绑哪些模块。
所以如果你真的想用变量来导入路径,你可以使用类似于 这个. 添加部分静态字符串到 require
可以让它工作。
var restOfThePath = 'svg/wizard-r.png'
require('../../resources/' + restOfThePath)
或者你可以只是 require
对象中,然后在你的代码中使用该对象。
也可以使用 {
在你 require
是你出现语法错误的原因。如果你删除它,那么错误就会消失。
..
const WizardContainer = props => {
ImagePathItems = [
{ path: require('../../resources/svg/wizard-r.png'), txtValue: "1" },
{ path: ('../../resources/svg/wizard-c.png'), txtValue: "2" },
{ path: ('../../resources/svg/wizard-s.png'), txtValue: "3" },
{ path: ('../../resources/svg/wizard-d.png'), txtValue: "4" }];
return (
<View style={styles.a}>
<View style={styles.b}>
<View style={styles.c}>
<FlatList
horizontal
data={ImagePathItems}
renderItem={({item}) =>
<Image
style={styles.tinyLogo}
source={item.path}
/>
}
keyExtractor={item => item.txtValue}
/>
</View>
</View>
</View>
);
};
export default WizardContainer;