简体   繁体   English

关于反应 state 和生命周期的初学者问题

[英]Beginner question about react state and lifecycle

I'll able to make this code work on index.js but I wanted to know if what's the different if I've wanted to imply this code into a App.js我将能够使此代码在 index.js 上运行,但我想知道如果我想将此代码暗示到 App.js 中是否有什么不同

this is index.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 />);

and this is for App.js btw I've already changed the index after trying to input the code in App.js but it show nothing I wonder what should I change.这适用于 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;

Technically, your index.js is the only file that is printing stuff on to your screen, everything else you have to export/import .从技术上讲,您的index.js是唯一在您的屏幕上打印内容的文件,您必须export/import所有其他内容。 If you are using create-react-app, you will see that index.js imports the <App /> component then renders it.如果你使用 create-react-app,你会看到index.js导入<App />组件然后渲染它。

Your App.js is not doing anything other than building and exporting the <App /> components.除了构建和导出<App />组件之外,您的App.js没有做任何事情。

If you are new to React, they have a tutorial and documentations on site , you would be able to find a lot more information from them!如果您是 React 新手,他们在网站上有教程和文档,您可以从他们那里找到更多信息!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM