我是編碼新手,所以我正在遵循本教學: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") );
P粉4269063692023-09-12 13:58:46
嘗試像這樣指定根元素:
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> );
P粉1388714852023-09-12 12:56:39
從控制台中的錯誤訊息來看,index.js 檔案中的 import 語句似乎有問題。該錯誤特別指出 ReactDOM 是從“react-dom/client”導入的,這不是有效的導入路徑。
要解決此問題,您應該更新 index.js 檔案中的匯入語句,以從「react-dom」而不是「react-dom/client」匯入 ReactDOM。這是更正後的導入語句:
import ReactDOM from 'react-dom';