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

React项目中quiz-app.png图片无法正常显示问题求助

React认证页面图片显示异常问题解决

问题描述

在React项目的认证页面中,尝试将assets文件夹内的quiz-app.png显示在屏幕60%宽度的区域,但页面仅显示图片占位图标。相关代码如下:

Auth组件代码

import React from 'react';
import './Auth.css';

const Auth = ({ onAuth, setUsername, setPassword }) => {
  return (
    <div className="auth-form-container">
      <input
        type="text"
        placeholder="Username"
        onChange={(e) => setUsername(e.target.value)}
        className="auth-input"
      />
      <input
        type="password"
        placeholder="Password"
        onChange={(e) => setPassword(e.target.value)}
        className="auth-input"
      />
      <button onClick={() => onAuth('login')} className="auth-button">Login</button>
      <button onClick={() => onAuth('register')} className="auth-button">Sign Up</button>
    </div>
  );
};

export default Auth;

Auth.css代码

.auth-form-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  
  .auth-input {
    width: 100%;
    max-width: 300px;
    margin: 10px 0;
    padding: 10px;
    border-radius: 25px;
    border: 1px solid #ccc;
    box-sizing: border-box;
  }
  
  .auth-button {
    width: 100%;
    max-width: 300px;
    margin: 10px 0;
    padding: 10px;
    border-radius: 25px;
    border: none;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    font-size: 16px;
  }
  
  .auth-button:hover {
    background-color: #0056b3;
  }

App.js代码

import React, { useState } from 'react';
import axios from 'axios';
import './App.css';
import Auth from './components/Auth';
import Exam from './components/Exam';
import ProfileCard from './components/ProfileCard';
import AdminPanel from './components/AdminPanel';

const App = () => {
  const [mode, setMode] = useState('auth'); // 'auth' or 'exam'
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [questions, setQuestions] = useState([]);
  const [answers, setAnswers] = useState({});
  const [score, setScore] = useState(null);
  const [error, setError] = useState('');
  const [isAdmin, setIsAdmin] = useState(false);

  const handleAuth = async (endpoint) => {
    try {
      const response = await axios.post(`http://localhost:4000/${endpoint}`, { username, password });
      if (response.status === 200 || response.status === 201) {
        setMode('exam');
        fetchQuestions();
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Error during authentication');
    }
  };

  const fetchQuestions = async () => {
    try {
      const response = await axios.get('http://localhost:4000/questions');
      setQuestions(response.data);
    } catch (err) {
      setError('Error fetching questions');
    }
  };

  const handleSubmit = async () => {
    try {
      const response = await axios.post('http://localhost:4000/submit', { answers });
      setScore(response.data.score);
    } catch (err) {
      setError('Error submitting answers');
    }
  };

  return (
    <div className="app-container">
      {mode === 'auth' && (
        <div className="auth-container">
          <div className="auth-image">
            <img src="/assets/quiz-app.png" alt="Quiz" />
          </div>
          <div className="auth-form">
            <Auth onAuth={handleAuth} setUsername={setUsername} setPassword={setPassword} />
          </div>
        </div>
      )}
      {mode === 'exam' && (
        <div className="exam-container">
          <div className="exam-questions">
            <Exam questions={questions} handleAnswerChange={(qId, option) => setAnswers(prev => ({ ...prev, [qId]: option }))} handleSubmit={handleSubmit} />
          </div>
          <div className="profile-card">
            <ProfileCard />
          </div>
          {isAdmin && (
            <div className="admin-panel">
              <AdminPanel onSwitchToAuth={() => setMode('auth')} />
            </div>
          )}
          <button className="admin-panel-button" onClick={() => setIsAdmin(!isAdmin)}>Admin Panel</button>
        </div>
      )}
    </div>
  );
};

export default App;

App.css代码

/* General Styles */
body {
  margin: 0;
  font-family: Arial, sans-serif;
}

/* Main Container */
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* Auth Container */
.auth-container {
  display: flex;
  width: 100%;
  height: 100%;
}

/* Auth Image Section */
.auth-image {
  width: 60%;
  height: 100%; /* Ensure it covers the full height */
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f4f4f4; /* Optional background color */
  overflow: hidden; /* Hide any overflow */
}

.auth-image img {
  width: 100%;
  height: 100%; /* Ensure it covers the full height */
  object-fit: cover; /* Scale the image to cover the container */
}

/* Auth Form Section */
.auth-form {
  width: 40%;
  height: 100%; /* Ensure it covers the full height */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: white;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* Auth Form Inputs */
.auth-input {
  width: 80%;
  padding: 10px;
  margin: 10px 0;
  border: 1px solid #ccc;
  border-radius: 25px;
}

.auth-button {
  width: 80%;
  padding: 10px;
  margin: 10px 0;
  border: none;
  border-radius: 25px;
  background-color: #007bff;
  color: white;
  font-size: 16px;
  cursor: pointer;
}

.auth-button:hover {
  background-color: #0056b3;
}

/* Exam Container */
.exam-container {
  display: flex;
  width: 100%;
  height: 100%;
}

/* Exam Questions Section */
.exam-questions {
  width: 66%;
  padding: 20px;
  overflow-y: auto;
}

/* Profile Card Section */
.profile-card {
  width: 33%;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* Admin Panel Button */
.admin-panel-button {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 10px 20px;
  border: none;
  border-radius: 25px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  font-size: 16px;
  z-index: 1000; /* Ensure button is above other content */
}

.admin-panel-button:hover {
  background-color: #0056b3;
}

/* Admin Panel */
.admin-panel {
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 20px;
}

问题排查与解决方案

核心原因

React项目中图片资源的访问路径规则取决于文件存放位置:

  • 放在public目录下的资源可以用绝对路径(如/assets/quiz-app.png)直接访问
  • 放在src目录下的资源必须通过import导入后使用,不能直接用绝对路径

具体解决步骤

情况1:assets文件夹在public目录下

  1. 验证文件结构:确认public/assets/quiz-app.png存在,文件名大小写与代码中一致(React项目对文件名大小写敏感)
  2. 检查文件完整性:打开图片文件确认未损坏,格式正确(如png/jpg)
  3. 清除缓存:执行npm start重启项目,或清除浏览器缓存后刷新页面

情况2:assets文件夹在src目录下

修改App.js中的图片导入方式:

// 在文件顶部导入图片资源(路径根据实际项目结构调整)
import quizImage from './assets/quiz-app.png';

// 然后修改img标签的src属性
<img src={quizImage} alt="Quiz" />

额外验证

当前CSS中.auth-image和.auth-image img的样式设置正确,确保图片能填满60%宽度的容器:

.auth-image {
  width: 60%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.auth-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:20:54