【问题标题】:How to display images in React Native which are stored using nodejs?如何在 React Native 中显示使用 nodejs 存储的图像?
【发布时间】:2021-07-12 20:08:54
【问题描述】:

我想在我的 react native 中显示从 API 获取的图像

【问题讨论】:

标签: node.js reactjs react-native


【解决方案1】:

至少有一些方法可以实现这一点。它们都基于来自 React Native 的 <Image /> 组件。

  1. 第一种方法是从 API 获取图片 URL,然后将其用作来源。
  2. 第二个是在 API 端将图像编码为 base64 字符串,并将其发送到 react native 应用程序。

这是一个单一的 React Native 组件的基本示例,该组件执行 URL 或 Base64 图像的获取并显示它:

import React, { useState, useEffect } from 'react';
import { View, Image, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  someImage: {
    width: 100,
    height: 100,
  },
});

const DisplayAnImage = () => {
  const [image, setImage] = useState('');

  useEffect(() => {
    fetch('https://your.api.address/which/returns/images')
    .then((response) => response.json())
    .then((json) => {
      setImage(json.someUrlOrBase64);
    })
    .catch((error) => {
      console.error(error);
    });
  }, []);

  return (
    <View>
      <Image
        style={styles.someImage}
        source={{
          uri: image,
        }}
      />
    </View>
  );
}

export default DisplayAnImage;

图片大小要设置好,否则不可见。

更多细节可以在官方文档中找到:https://reactnative.dev/docs/image

【讨论】:

  • 感谢 i9or 的快速响应,我给你带来了好消息它对我有用。 hhh 但我想知道相同的方法是否适用于视频和录制音频?再次感谢。
  • 不幸的是,标准反应原生库中没有可用的视频组件。您必须寻找外部库或自己编写。
  • 再次感谢 i9or 的快速回复,希望您有愉快的一天。
猜你喜欢
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多