簡體   English   中英

關於反應 state 和生命周期的初學者問題

[英]Beginner question about react state and lifecycle

我將能夠使此代碼在 index.js 上運行,但我想知道如果我想將此代碼暗示到 App.js 中是否有什么不同

這是 index.js

import React from 'react';
import ReactDOM from 'react-dom/client';


const root = ReactDOM.createRoot(document.getElementById('root'));


class Clock extends React.Component{
  constructor(props){
    super(props);
    this.state = {time: new Date()};
  }
  render (){
 return (
  <div>
    <h1> Time: {this.state.time.toLocaleTimeString()}</h1>
  </div>
 )
}
}
root.render(<Clock />);

這適用於 App.js 順便說一句,我在嘗試在 App.js 中輸入代碼后已經更改了索引,但它什么也沒顯示我想知道我應該改變什么。

import React, {Component} from "react";

class App extends Component{
  constructor(props){
    super(props);
    this.state = {time: new Date()};
  }

render(){
return (
  <div>
    <h1>Time: {this.state.time.toLocateTimeString()}</h1>
  </div>
);
}
}

export default App;

從技術上講,您的index.js是唯一在您的屏幕上打印內容的文件,您必須export/import所有其他內容。 如果你使用 create-react-app,你會看到index.js導入<App />組件然后渲染它。

除了構建和導出<App />組件之外,您的App.js沒有做任何事情。

如果您是 React 新手,他們在網站上有教程和文檔,您可以從他們那里找到更多信息!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM