【问题标题】:ReactNative - ImageBackground load local image with a delayReact Native - ImageBackground 延迟加载本地图像
【发布时间】:2019-08-20 15:17:57
【问题描述】:

我注意到,当我运行 react-native 应用程序时,我使用标签 <ImageBackground> 设置为背景的图像加载延迟近 2 秒,即使它们不是重图像 (~100K) 和它们存储在本地。

我也阅读了this answer,但它并没有解决我的问题。

这是我插入图片作为背景的简单代码:

<ImageBackground source={require('../images/ScanQR.png')} style={styles.backgroundImage}>
    <Text style={styles.domanda}>
      Example text
    </Text>
</ImageBackground>

【问题讨论】:

    标签: react-native imagebackground delay-load


    【解决方案1】:

    您可以在 App.js 中 require() 之前加载它们的图像。这样做:

    async function loadResourcesAsync() {
      await Promise.all([
        Asset.loadAsync([
          require('./assets/images/stock1.jpg'),      
          require('./assets/images/stock2.jpg'), 
          require('./assets/images/undraw1.png'), 
        ]),
        Font.loadAsync({
          // This is the font that we are using for our tab bar
          ...Ionicons.font,
          // We include SpaceMono because we use it in HomeScreen.js. Feel free to
          // remove this if you are not using it in your app      
          'open-sans-regular': require('./assets/fonts/OpenSans-Regular.ttf'),
          'open-sans-extrabold': require('./assets/fonts/OpenSans-ExtraBold.ttf'),
        }),
      ]);
    }
    

    我在这里使用 Expo,你不需要创建这个函数,它已经在 App.js 中,只需在 require() 函数中添加你的图像。

    我不知道这是否可以在没有 Expo 的 React Native 中工作。

    【讨论】:

    • 按照您的建议,上传图片的问题得到了解决,但反过来又会产生另一个问题。按下按钮时,会在移动到下一页之前选择片刻(约 1 秒)
    【解决方案2】:

    遵循@crodev,但对于使用 React 函数组件的人,您可以使用钩子来实现相同的结果。

    此外,您可以使用expo-app-loading 中的AppLoading 组件来保持启动画面,直到一切准备就绪。

    function useImages(images) {
      const [loaded, setLoaded] = useState(false);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        Asset.loadAsync(images)
          .then(() => setLoaded(true))
          .catch(setError);
      }, []);
    
      return [loaded, error];
    }
    
    export default function App() {
      const [imagesLoaded] = useImages([
          require('./assets/images/stock1.jpg'),      
          require('./assets/images/stock2.jpg'), 
          require('./assets/images/undraw1.png'), 
      ]);
    
      if (!imagesLoaded) {
        return <AppLoading />;
      }
      
      return <>...</>;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 2019-07-28
      • 2021-01-13
      • 1970-01-01
      • 2017-07-21
      • 2021-05-11
      • 1970-01-01
      相关资源
      最近更新 更多