我是新手,我制作了一個簡單的組件并將一些資料渲染到該組件中,但我在瀏覽器上看不到任何輸出,并且我在控制臺上收到此錯誤“react_dom_client__WEBPACK_IMPORTED_MODULE_1__.render is not a function”。
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
// import App from './App';
// import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';
ReactDOM.render(<Counter />, document.getElementById("root"));
// registerServiceWorker();
計數器.jsx
import React, {Component} from 'react';
class Counter extends Component {
state = {
count : 1,
}
render() {
return (
<div>
<span>{this.formatCount()}</span>
</div>
);
}
formatCount() {
const {count} = this.state;
return count === 0 ? 'Zero' : count;
}
}
export default Counter;
uj5u.com熱心網友回復:
您需要創建一個根,然后使用它進行渲染:
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Counter />);
uj5u.com熱心網友回復:
您的 Counter 類組件缺少一些東西,見下文:
class Counter extends Component {
// You need to call the Component constructor so the class Counter inherit
// the React Component properties and methods
constructor(props) {
super(props);
// You need to add the state to 'this' so you can reference it later
this.state = {
count: 1
};
}
// Create the function before you call it, that is why I move
// it at the top of the render
formatCount() {
const {count} = this.state;
return count === 0 ? 'Zero' : count;
}
render() {
return (
<div>
<span>{this.formatCount()}</span>
</div>);
}
}
// This is fine as long as you have a div with id of root
ReactDOM.render(<Counter />, document.getElementById("root"));
希望有幫助
uj5u.com熱心網友回復:
擴展組件應該是擴展 React.Component。此外,您應該將 formatCount() 函式保持在 return 陳述句之上。
class Counter extends React.Component {
state = {
count : 1,
}
formatCount() {
const {count} = this.state
return count === 0 ? 'Zero' : count
}
render() {
return (
<div>
<span>{this.formatCount()}</span>
</div>
)
}
}
uj5u.com熱心網友回復:
嘗試這個:
import React from 'react'
import ReactDOM from 'react-dom/client'
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';
const root = ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<Counter />
</React.StrictMode>);
React.StrictMode是一種用于突出顯示應用程式中潛在問題的工具,StrictMode 不會呈現任何可見的 UI。它為其后代激活額外的檢查和警告。有關更多資訊,請參閱https://reactjs.org/docs/strict-mode.html。
uj5u.com熱心網友回復:
在您的檔案中,您需要根據需要創建根目錄然后渲染它的版本index.js來更新代碼。react18
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<Counter />);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/491139.html
標籤:javascript 反应
