我想根据传递下来的道具来渲染图像。第一个注释掉的 filePath 是源文件。我尝试了几种变体,但它总是给我同样的错误。 React 文档并没有真正涵盖在 30 多种不同场景的情况下你会做什么。我可以向该组件添加一个状态并让它包含所有文件变体,但这似乎比必要的工作更多。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
包含所有可能的图像,然后在Image source
传递图标名称。
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]}/>
)
}
So if this.props.icon.icon
is sample1
,它将加载该图像。
您还可以创建一个函数来验证请求的图标是否存在,以及如果不返回默认图标
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)}/>
)
}
这个问题描述了您不能需要动态文件,并提出了一个示例,说明在可能的选项很少的情况下如何处理它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)