You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo本地图片路径正确却无法显示的排查求助

React Native Expo本地PNG图片无法显示问题求助

存储在assets目录的本地PNG图片,尽管路径和样式均设置正确,但始终无法显示,仅外链的非本地图片可以正常展示。

已尝试的排查步骤

  • 检查assets目录中图片的路径,确保无误
  • 验证图片格式为PNG,并更换不同图片排除单图问题
  • 确认Image组件的样式正确,容器已分配对应空间
  • 验证图片已正确导入并在Image组件的source属性中引用

经过以上操作,本地图片仍无法正常渲染,期望它能像外链图片一样在应用中正确显示。

环境配置

react-native-cli: 2.0.1
react-native: 0.72.12
expo SDK version: 49.0.0

代码示例

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, TextInput, KeyboardAvoidingView, SafeAreaView, Image } from 'react-native'
import { useDispatch } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
import { login } from '../store/reducers/user'
import AuthAPI from '../services/authAPI'
import FontAwesome from 'react-native-vector-icons/FontAwesome'
import AsyncStorage from '@react-native-async-storage/async-storage';

// Custom input component
const CustomInput = ({ icon, placeholder, onChangeText, value, secureTextEntry, error, onFocus, onBlur }) => {
  return (
    <View style={styles.inputContainer}>
      <FontAwesome name={icon} style={styles.icon} />
      <TextInput
        placeholder={placeholder}
        onChangeText={onChangeText}
        value={value}
        secureTextEntry={secureTextEntry}
        style={styles.input}
        onFocus={onFocus}
        onBlur={onBlur}
      />
      {error && <Text style={styles.error}>{error}</Text>}
    </View>
  );
};

function SigninScreen({ setIsLoggedIn}) {
  const dispatch = useDispatch(); 

  const [signinEmail, setSigninEmail] = useState("");
  const [signinPassword, setSigninPassword] = useState("");
  const [errors, setErrors] = useState({}); // State to store errors
  const navigation = useNavigation();

  const handleInputFocus = () => {
    // Clear errors when input is focused
    setErrors({});
  };

  const handleSignin = async () => {
    // Validation logic
    const errors = {};
    if (!signinEmail.trim()) {
      errors.email = "L'email est requis";
    }
    if (!signinPassword.trim()) {
      errors.password = "Le mot de passe est requis";
    }

    // Si des erreurs sont détectées, arrêtez le processus de connexion
    if (Object.keys(errors).length > 0) {
      setErrors(errors);
      return;
    }

    try {
      // Data in json
      const data = await AuthAPI.signin({ password: signinPassword, email: signinEmail });

      if (data.result) {
        dispatch(login({
          token: data.token,
          email: signinEmail
        }))
        AsyncStorage.setItem('token', data.token)
        AsyncStorage.setItem('isLoggedIn', JSON.stringify(true));
        setIsLoggedIn(true);
        setSigninEmail("");
        setSigninPassword("");
        
      } else {
        alert("Mauvais email ou mot de passe");
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <SafeAreaView>
      <KeyboardAvoidingView style={styles.main}>
        <Text style={styles.title}>Sign In</Text>
        <View style={styles.logoContainer}>
          <Image style={styles.logo} source={require('../assets/logo_em.png')} />
        </View>
        <View style={styles.form}> 
          <CustomInput
            icon="user-o"
            placeholder="Email"
            onChangeText={(value) => setSigninEmail(value)}
            value={signinEmail}
            error={errors.email} // Pass error message to custom input
            onFocus={handleInputFocus} // Clear errors when input is focused
          />
          <CustomInput
            icon="lock"
            placeholder="Password"
            secureTextEntry={true}
            onChangeText={(value) => setSigninPassword(value)}
            value={signinPassword}
            error={errors.password}
            onFocus={handleInputFocus} // Clear errors when input is focused
          />
          <TouchableOpacity style={{ marginBottom: 6, marginTop: -5 }}>
            <Text style={{ fontWeight: 'bold', marginLeft: '40%' }}>Forgot your password ?</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.button} onPress={handleSignin}>
            <Text style={styles.buttonText}>Sign In</Text>
          </TouchableOpacity>
          <Text style={{ fontWeight: 'bold', marginBottom: 5 }}>Don't have an account yet ? </Text>
          <TouchableOpacity style={styles.button2} onPress={() => navigation.navigate("Signup")}>
            <Text style={styles.buttonText2}>Sign Up</Text>
          </TouchableOpacity>
        </View>

      </KeyboardAvoidingView>

    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  main: {
    width: '100%',
    height: '100%',
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    color: 'black',
    textAlign: 'center',
    fontSize: 30,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  logoContainer: {
    flex:1
  },
  logo: {
    width: 50,
    height: 50,
  },
  form: {
    width: '80%',
    alignItems: 'center'
  },
  inputContainer: {
    position: 'relative',
    marginBottom: 10,
    width: '100%',
  },
  icon: {
    position: 'absolute',
    fontSize: 20,
    color: 'black',
    zIndex: 1,
    left: 10,
    top: 13,
  },
  input: {
    backgroundColor: "white",
    borderWidth: 1,
    borderColor: "black",
    borderRadius: 10,
    padding: 10,
    width: '100%',
    paddingLeft: 40, // Adjusted for icon width and position
  },
  button: {
    backgroundColor: 'black',
    borderRadius: 10,
    padding: 10,
    marginBottom: 10,
    width: '100%',
    alignItems: 'center',
    marginTop: '5%'
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
  },
  button2: {
    borderRadius: 10,
    padding: 10,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: 'black',
    width: '100%',
    alignItems: 'center',
  },
  buttonText2: {
    color: 'black',
  },
  error: {
    color: 'red',
    marginTop: 5,
    textAlign: 'center', // Center the error message
  },
});

export default SigninScreen;

项目结构

项目根目录下包含assets文件夹,当前代码文件位于screens目录中,图片路径../assets/logo_em.png对应正确的层级关系。

恳请帮忙排查该问题并提供可行的解决方案,感谢您的见解与建议!

内容的提问来源于stack exchange,提问作者remig17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:34:53