首页 > 解决方案 > 图片未在 React Native Web App 中显示。当我为 Android 或 iOS 构建时出现,但在使用 react-scripts start 时不显示

问题描述

我正在尝试在使用 react-scripts start 运行的 React Native Web App 中显示图像。当我为 iOS 或 Android 构建应用程序时,图像看起来非常好(使用 expo),但是当我为 Web 应用程序构建它时,图像无法加载。这是加载图像的 Home 组件的代码片段

import React from "react";
import { ScrollView, ActivityIndicator, StyleSheet, Image, ImageBackground } from "react-native";
import UserList from "./user-list";
import Header from './header';
import sanityClient from './assets/client' 
import BackButton from './back-button'
import User from './user'
// import {Asset} from 'expo-asset';

// const imageURI = Asset.fromModule(require('./arrow.png')).uri;

const image = require('./assets/aoeu.jpg');

class Home extends React.Component {
  state = {
    user: {},
    loading: true
  };

  componentDidMount() {
    // TODO: get users
    this.getUser();
  }

  async getUser() {
    sanityClient.fetch(`*[ _type == "user" && emailAddress.current == "dwight@viamaven.com"]`)
      .then((data) => {
        console.log(data);
        this.setState({user: data[0], loading: false});
        console.log(this.state.user);
      })
      .catch((err) => console.error(err))
    // const res = await fetch("https://randomuser.me/api/?results=20");
    // const { results} = await res.json();
    // // console.log(results)
    // this.setState({users: [...results], loading: false});
  }

  render() {
    return (
      <ScrollView
        noSpacer={true}
        noScroll={true}
        style={styles.container}
        showVerticalSCrollIndicator = {false}
        showHorizontalScrollIndicator = {false}
      >
          {this.state.loading ? (
          <ActivityIndicator
            style={[styles.centering, styles.gray]}
            color="#5d38aa"
            size="large"
          />
        ) : (
          <View>
            <Header title={this.state.user.name} />
            <View>
              <Image
                source={require('./arrow.png')}
                style={styles.image}
              />
            </View>
            <User />
            
          </View>
        )}
      </ScrollView>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    backgroundColor: "white",
    width: '375px',
    height: '812px',
    // top: '50px',
  },
  centering: {
    alignItems: "center",
    justifyContent: "center",
    padding: 8,
    height: '100vh'
  },
  image: {
    width: '50px',
    height: '50px',
    marginRight: 20,
    boxShadow: "0 1px 2px 0 rgba(0,0,0,0.1)"
  }
});

export default Home;

这是存储整个项目的 GitHub 存储库的链接https://github.com/nimbusdin/stackreactnative

标签: imagereact-nativeweb-applications

解决方案


尝试以这种方式导入。

    import image = './assets/aoeu.jpg';

如果您使用的是 TS,则会出现错误:类型 'string' 不可分配给类型 'ImageSourcePropType'。否则它会工作得很好。


推荐阅读