我是編碼新手,所以我正在遵循本教程:https://www.sitepoint.com/react-tutorial-build-calculator-app/ 我無法渲染任何元素。這是運行網絡應用程序時控制臺顯示的內容
這是我的 App.js 代碼:
import Wrapper from "./components/Wrapper.js"; import Screen from "./components/Screen.js"; import ButtonBox from "./components/ButtonBox.js"; import Button from "./components/Button.js"; const btnValues = [ ["C", "+-", "%", "/"], [7, 8, 9, "X"], [4, 5, 6, "-"], [1, 2, 3, "+"], [0, ".", "="], ]; const App = () => { return ( <Wrapper> <Screen value="0" /> <ButtonBox> { btnValues.flat().map((btn, i) => { return ( <Button key={i} className={btn === "=" ? "equals" : ""} value={btn} onClick={() => { console.log(`${btn} clicked!`); }} /> ); }) } </ButtonBox> </Wrapper> ); }; export default App;
然后這是index.js:
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById("root") );
嘗試像這樣指定根元素:
import React from 'react'; import ReactDOM from 'react-dom'; import { createRoot } from 'react-dom/client'; import './index.css'; import App from './App'; const root = createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> );
從控制臺中的錯誤消息來看,index.js 文件中的 import 語句似乎存在問題。該錯誤特別指出 ReactDOM 是從“react-dom/client”導入的,這不是有效的導入路徑。
要解決此問題,您應該更新 index.js 文件中的導入語句,以從“react-dom”而不是“react-dom/client”導入 ReactDOM。這是更正后的導入語句:
import ReactDOM from 'react-dom';