如果远程图像失败,是否可以加载本地图像?
例如,我有以下代码:
- <Image style={ styles.userImage }
- source={ { uri: http://example.com/my_image.jpg } }
- onError={(error) => ...}
- />
例如,我没有访问http://example.com/my_image.jpg的权限,我将在onError中收到错误.有没有办法加载本地图像?
使用组件’状态.在构造函数中设置初始url:
- this.state = { image: { uri: 'http://example.com/my_image.jpg' } }
创建onError处理程序:
- onError(error){
- this.setState({ image: require('your_local_image.path')})
- }
然后将它们组合在一起:
- <Image style={ styles.userImage }
- source={ this.state.image }
- onError={ this.onError.bind(this) }
- />