React应用打开空白页求助:点击index.html无内容显示
Hey there! Let's work through getting your React app displaying properly—since you're new to React, I'll break down each issue clearly so you understand what's going wrong.
1. Critical Syntax Error in Main.js
Looking at your Main.js code, you accidentally used an opening <HashRouter> tag instead of a closing </HashRouter> at the end of your component. This breaks the entire component tree structure, so React can't render anything below the title.
Fixed Main.js snippet:
import React, { Component } from "react"; import { Route, NavLink, HashRouter } from "react-router-dom"; import Home from "./Home"; import Stuff from "./Stuff"; import Contact from "./Contact"; class Main extends Component { render() { return ( <HashRouter> <div> <h1>Simple SPA</h1> <ul className="header"> <li><NavLink to="/">Home</NavLink></li> <li><NavLink to="/stuff">Stuff</NavLink></li> <li><NavLink to="/contact">Contact</NavLink></li> </ul> <div className="content"> <Route path="/" component={Home}/> <Route path="/stuff" component={Stuff}/> <Route path="/contact" component={Contact}/> </div> </div> </HashRouter> {/* This was incorrectly <HashRouter> before */} ); } } export default Main;
2. Misplaced CSS in index.js
You added the .active class styles directly in index.js, which won't work in a standard setup. Move that CSS rule into your index.css file so it applies correctly to your active navigation links:
Updated index.css (add at the end):
.active { background-color: #0099FF; }
3. Route Matching Issue (Avoid Duplicate Content)
Right now, your Home route (path="/") will match every URL (since all routes start with /). This means when you navigate to /stuff or /contact, the Home component will still render alongside them. Fix this by adding the exact prop to the Home route:
Fixed Route section in Main.js:
<div className="content"> <Route exact path="/" component={Home}/> {/* Add exact here */} <Route path="/stuff" component={Stuff}/> <Route path="/contact" component={Contact}/> </div>
4. Directly Opening index.html Won't Work (File Protocol Restriction)
On Ubuntu (and all modern browsers), opening index.html directly with the file:// protocol blocks ES module imports (like your import React from "react" lines) due to cross-origin security rules. You need to serve your app via a local web server.
Here's an easy way to do this:
- Make sure you have Node.js installed (check with
node -vin your terminal) - In your project root directory, run:
npx serve - This will start a local server (usually at
http://localhost:3000). Open that URL in your browser, and your app should render correctly.
5. Double-Check Dependencies Are Installed
Since you built this from an example, make sure you've installed all required packages. Run this in your project root:
npm install react react-dom react-router-dom
Once you fix these issues, your SPA should display the navigation bar and content sections correctly!
内容的提问来源于stack exchange,提问作者Bruce Espeschit

