React新手求助:页面添加按钮后无法显示(已添加root容器)
Hey there! Let's troubleshoot why your React button isn't showing up. From the code snippet you shared, there are a few common issues that might be blocking it—let's break them down and fix things step by step.
<link> tag Your code cuts off at <link rel="stylesh...—this incomplete HTML tag will mess up the page's parsing. Either finish it properly (like <link rel="stylesheet" href="your-stylesheet.css">) or delete it entirely if you don't need custom styles right now.
React doesn't render elements automatically—you need to explicitly create the button element (either with raw React API or JSX) and mount it to your root div. Here are two working approaches:
Option 1: Use raw React API (no JSX)
Add this script right after your root div in the <body>:
<script> // Create a button element using React's createElement method const myButton = React.createElement('button', null, 'Click Me!'); // Mount the button to the #root div ReactDOM.render(myButton, document.getElementById('root')); </script>
Option 2: Use JSX (cleaner syntax)
JSX needs to be transpiled to regular JavaScript, so you'll need to add the Babel CDN script. Here's the full corrected code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <!-- Add Babel to transpile JSX --> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <!-- Either complete or remove this stylesheet link --> <!-- <link rel="stylesheet" href="your-styles.css"> --> </head> <body> <div id="root"></div> <!-- Use type="text/babel" for JSX code --> <script type="text/babel"> // Define a simple button component function MyButton() { return <button>Click Me!</button>; } // Mount the component to the #root div ReactDOM.render(<MyButton />, document.getElementById('root')); </script> </body> </html>
Ensure the React and ReactDOM scripts load before your custom React code—if they load after, you'll get "React is not defined" errors that prevent rendering.
Hit F12 to open the developer tools console. Any syntax errors, missing dependencies, or unclosed tags will show up here, and they're usually the root cause of hidden elements.
Give these fixes a go, and your button should appear as expected! If you hit more snags, share your full code and any console error messages you see.
内容的提问来源于stack exchange,提问作者Zhaoyuxuan

