[英]React Native - Require Image source with default source
我正在從 API 獲取 ID 列表,其中大部分我在本地存儲了一個關聯的圖像。 但是,某些 ID 沒有圖像,因此在嘗試要求其來源時會返回錯誤。
這是我獲取來源的方式:
<Image style={{height: '100%', width: '100%'}} source={require('../assets/character-images/' + this.character.id + '.jpg'))}/>
我怎樣才能有一個默認的后備源? 如果找不到,我什至不介意不加載圖像......我無法擺脫這個錯誤。 謝謝。
您可以處理圖像上的 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}
/>
);
}
}
由於您正在加載的資產是在項目中預定義的,為什么不簡單地檢查您是否能夠加載它?
比如說你有character-images/1
, character-images/2
, character-images/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}/>
您可以使用這個小函數來查看圖像是否存在,然后動態決定是否渲染它:
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')}/>;
);
})}
或者如果您根本不想渲染 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')}/>;
);
})}
要動態檢查文件是否存在,您可以使用fs.exist然后將其添加到可用 id 的數組中(如果存在),然后在渲染時您可以檢查要渲染的 id 是否可用以及它是否可用不可用顯示默認圖像。
您可以使用如下代碼來檢查文件是否存在。
checkIfFileExists=(id)=>{
RNFetchBlob.fs.exists(PATH_OF_FILE).then((exist) => {
return exist;
})
.catch(() => return false)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.