问题描述
我想根据传递的道具来渲染图像.第一个注释掉的 filePath 是源是什么.我尝试了几种变体,但它一直给我同样的错误.react 文档并没有真正涵盖您在拥有 30 多种不同场景的情况下会做什么.我可以向这个组件添加一个状态并让它包含所有文件变体,但这似乎比必要的工作要多.https://facebook.github.io/react-native/docs/images
I want to render an image based on what what props is passed down. The first commented out filePath is what the source is. I have tried several variations, but it keeps giving me this same error. The react documentation doesn't really cover what you would do on cases where you have 30+ different scenarios. I could just add a state to this component and have it include all the file variations, but that seems like more work than necessary. https://facebook.github.io/react-native/docs/images
class Weather extends React.Component {
render() {
// let filePath = "./weatherimg/01d.png";
let filePath = `./weatherimg/${this.props.icon.icon}.png`;
let filePath2 = this.props.icon ? require(filePath) : require(filePath);
return (
<View >
<Text>{this.props.location} {this.props.data[0]}</Text>
<Text>{this.props.data[1]}</Text>
<Text>Low {this.props.temps.low}, High {this.props.temps.high}</Text>
<Text>{this.props.icon.description}</Text>
<View style={{width: 60, height: 60}}>
<Image source={filePath2} style={{flex: 1}} />
</View>
</View>
);
}
}
推荐答案
如果您有大量可能的图像,您可以创建一个包含所有可能图像的 object
,然后在 图片来源
传递图标名称.
If you have a large list of possible images you can create an object
that contains all possible images, and then in Image source
pass the icon name.
let icons = {
'sample1': require('./weatherimg/sample1.png')
,'sample2': require('./weatherimg/sample2.png')
,'sample3': require('./weatherimg/sample3.png')
}
render(){
return(
<Image source={icons[this.props.icon.icon]}/>
)
}
因此,如果 this.props.icon.icon
是 sample1
,它将加载该图像.
So if this.props.icon.icon
is sample1
, it will load that image.
您也可以创建一个函数来验证请求的图标是否存在,如果不返回默认图标
Also you can create a function to validate if requested icon exists or not, and in case of not return a default icon
let icons = {
default: require('./weatherimg/default.png')
,'sample1': require('./weatherimg/sample1.png')
,'sample2': require('./weatherimg/sample2.png')
,'sample3': require('./weatherimg/sample3.png')
}
validateIcons(icon){
return (icons[icon]) ? icons[icon] : icons['default'];
}
render(){
return(
<Image source={this.validateIcons(this.props.icon.icon)}/>
)
}
这个问题描述你不能要求动态文件,并提出了一个例子,说明在可能的选项很少的情况下如何处理它.
This issue describes that you can`t require dynamic files, and proposes an example on how to deal with it in case that there are few possible options.
这篇关于调用 require 期望正好有 1 个字符串文字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!