简体   繁体   中英

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

this is 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.

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 . If you are using create-react-app, you will see that index.js imports the <App /> component then renders it.

Your App.js is not doing anything other than building and exporting the <App /> components.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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