react-native – 加载远程映像失败后加载本地映像

前端之家收集整理的这篇文章主要介绍了react-native – 加载远程映像失败后加载本地映像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果远程图像失败,是否可以加载本地图像?

例如,我有以下代码

  1. <Image style={ styles.userImage }
  2. source={ { uri: http://example.com/my_image.jpg } }
  3. onError={(error) => ...}
  4. />

例如,我没有访问http://example.com/my_image.jpg的权限,我将在onError中收到错误.有没有办法加载本地图像?

使用组件’状态.在构造函数中设置初始url:
  1. this.state = { image: { uri: 'http://example.com/my_image.jpg' } }

创建onError处理程序:

  1. onError(error){
  2. this.setState({ image: require('your_local_image.path')})
  3. }

然后将它们组合在一起:

  1. <Image style={ styles.userImage }
  2. source={ this.state.image }
  3. onError={ this.onError.bind(this) }
  4. />

猜你在找的React相关文章