React入门遇阻:ReactDOM无法渲染组件,报语法与引用错误
Fixing Uncaught Syntax & Reference Errors in Your React CDN Setup
Hey there, let's break down what's causing those errors and fix your React setup step by step!
Key Issues in Your Current Code
- Incorrect Script Loading Order: Your
app.jsis loaded before React, ReactDOM, and Babel. Since your app depends on these libraries, they need to be loaded first so their global variables are available when your code runs. - Wrong ReactDOM CDN File: You're using
react-dom-server.browser.development.js—this is built for server-side rendering. You need the standard browser-focusedreact-dom.development.jsinstead. importStatements Don't Work with CDN Scripts: When loading React via CDN, it exposes globalReactandReactDOMvariables automatically. You don't need toimportthem; just use the global names directly.- Using
classInstead ofclassName: In React JSX,classis a reserved JavaScript keyword, so you must useclassNameto assign CSS classes to elements. - Missing Babel Processing for JSX: Your
app.jscontains JSX syntax, which needs to be transpiled by Babel to plain JavaScript. You need to mark your React script withtype="text/babel"so Babel knows to process it.
Corrected Code
HTML
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="./main.css"> </head> <body> <div id="p1"></div> <div class="person"> <h1>Akshar</h1> <p>Your Age: 27</p> </div> <!-- Load dependencies FIRST --> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"></script> <!-- Mark your React script with type="text/babel" --> <script type="text/babel" src="./app.js"></script> </body> </html>
app.js
// No imports needed—React and ReactDOM are global variables function Person() { return ( <div className="person"> {/* Changed class to className */} <h1>Max</h1> <p>Your Age: 28</p> </div> ); } ReactDOM.render(<Person/>, document.querySelector('#p1'));
CSS (unchanged)
.person { display: inline-block; margin: 10px; border: 1px solid #eee; box-shadow: 0 2px 2px #ccc; width: 200px; padding: 20px; }
Quick Note for CORS Issues
If you run into cross-origin errors when loading app.js with type="text/babel", you can move your React code directly into the HTML file instead:
<script type="text/babel"> function Person() { return ( <div className="person"> <h1>Max</h1> <p>Your Age: 28</p> </div> ); } ReactDOM.render(<Person/>, document.querySelector('#p1')); </script>
内容的提问来源于stack exchange,提问作者InNeedOfKnowledge
相关产品推荐
相关产品推荐

