Javascript React Native-需要具有默认源的图像源

Javascript React Native-需要具有默认源的图像源,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在从一个API获取一个ID列表,其中大多数ID都有一个本地存储的关联映像。但是,有些ID没有映像,因此在尝试要求其源时返回错误 以下是我获取来源的方式: <Image style={{height: '100%', width: '100%'}} source={require('../assets/character-images/' + this.character.id + '.jpg'))}/> 如何拥有默认的回退源?如果找不到图像,我甚至不介意不加载它。。。我就是

我正在从一个API获取一个ID列表,其中大多数ID都有一个本地存储的关联映像。但是,有些ID没有映像,因此在尝试要求其源时返回错误

以下是我获取来源的方式:

<Image style={{height: '100%', width: '100%'}} source={require('../assets/character-images/' + this.character.id + '.jpg'))}/>


如何拥有默认的回退源?如果找不到图像,我甚至不介意不加载它。。。我就是无法摆脱这个错误。谢谢。

既然您正在加载的资产是在project中预定义的,为什么不简单地检查一下您是否能够加载它呢

例如,假设你有
字符图像/1
字符图像/2
字符图像/3
,那么你可以这样做:

const availableCharacterIds = ['1', '2', '3']
const assetToLoad = availableCharacterIds.includes(`${this.character.id}`) ? 
  require('../assets/character-images/' + this.character.id + '.jpg') : null
然后在渲染JSX中:

<Image style={{height: '100%', width: '100%'}} source={assetToLoad}/>

您可以处理图像上的onError事件,并呈现不同的图像。下面可以找到接受默认映像的示例组件

export default class ImageWithFailback extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: false
    };
  }
  _onError = () => {
    this.setState({ hasError: true });
  }
  render() {
    const failBackImage = <Image source={this.props.default} style={this.props.style} />;

    if (this.state.hasError) return failBackImage;

    return (
      <Image
        {...this.props}
        onError={this._onError}
        renderIndicator={_ => failBackImage}
      />
    );
  }
}
export default class ImageWithFailback扩展React.Component{
建造师(道具){
超级(道具);
此.state={
hasError:错误
};
}
_onError=()=>{
this.setState({hasError:true});
}
render(){
const failBackImage=;
如果(this.state.hasError)返回failBackImage;
返回(
failBackImage}
/>
);
}
}

您可以使用此小功能查看图像是否存在,然后动态决定是否渲染:

const tryRequire = (path) => {
  try {
   return require(`${path}`);
  } catch (err) {
   return null;
  }
};
然后在渲染方法中

{this.state.ids &&
    this.state.ids.map((id) => {
        return (
            <Image style={{height: '100%', width: '100%'}} source={this.tryRequire('../assets/character-images/' + id + '.jpg') !== null ? require('../assets/character-images/' + id + '.jpg') : require('../assets/fallbackimg.png')}/>;
        );
    })}
{this.state.ids&&
this.state.ids.map((id)=>{
返回(
;
);
})}
或者,如果您根本不想渲染img(没有回退img),您可以简单地添加一个过滤器

{this.state.ids &&
    this.state.ids
        .filter((id) => return this.tryRequire('../assets/character-images/' + id + '.jpg') === null)
        .map((id) => {
            return (
                <Image style={{height: '100%', width: '100%'}} source={this.tryRequire('../assets/character-images/' + id + '.jpg')}/>;
    );
})}
{this.state.ids&&
这个是.state.ids
.filter((id)=>返回此.tryRequire('../assets/character images/'+id+'.jpg')==null)
.map((id)=>{
返回(
;
);
})}

要动态检查文件是否存在,您可以使用,然后将其添加到可用id数组中(如果存在),然后在渲染时,您可以检查要渲染的id是否可用,如果不可用,则显示默认图像

您可以使用如下代码检查文件是否存在

checkIfFileExists=(id)=>{
RNFetchBlob.fs.exists(PATH_OF_FILE).then((exist) => {
    return exist;
})
.catch(() => return false)
}

谢谢,这很好,但我关心的是,当我尝试动态地执行此操作时,我必须跟踪可用ID的列表。有没有办法检查图像源是否存在并将其动态添加到此“availableCharacterIds”中?