簡體   English   中英

如何在顯示加載屏幕時加載圖像反應本機

[英]How do I load an image while displaying loading screen react native

我試圖在刪除加載屏幕之前在我的頁面上加載個人資料照片,但不知道如何。 現在我的渲染 function 中有一個“if”語句,它要么返回加載屏幕,要么返回頁面的 rest。

當我從 firebase 獲取個人資料照片和用戶名等的 URL 時,我會顯示加載屏幕。 但我不知道如何在圖像從 URL 下載到我的應用程序時顯示相同的加載屏幕,因為我是在 JSX 代碼中下載的。

這是我的渲染語句中的代碼:

render(){
    if (this.state.loading == true) {
        return (
            //returns jsx of a full page loading screen
        )
    }
    return (
        <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 50, marginBottom: 50 }}>
            <Image style={{ width: 150, height: 150, borderRadius: 500 }} source={{ uri: this.state.userimage }} />
        </View>
    )
}

這段代碼被簡化了,但這基本上就是我正在做的。

現在,當我從 firebase 等加載 URL 時,會顯示加載屏幕,但隨后我設置了 this.state。加載屏幕仍然需要幾秒鍾,因為加載屏幕仍然是假的,但加載屏幕仍然沒有已經加載。

有人可以告訴我如何在我的加載屏幕仍然打開時預加載圖像或其他一些簡單的方法來加載圖像,然后立即顯示它嗎?

謝謝!

我將react-native-fast-image用於我的圖像及其預加載function。

一種方法是在 DOM 調用它之前在后台獲取圖像。

下面是一些演示此功能的簡單代碼。

import React from 'react';

const IMAGE_URL = "https://via.placeholder.com/150";

const preloadImage = (url) => {
  return fetch(url);
}

export const App = (props) => {
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    // comment out this line and the image is not loaded until it is needed in the dom
    preloadImage(IMAGE_URL);

    setTimeout(() => setLoading(false), 3000);
    }, []
  );

  return (loading ? <span>Loading</span> : <img src={IMAGE_URL} />);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM