The React components
Component, similar to the JS function, which takes arbitrary arguments (props) and returns the React element used to describe the page presentation
Components fall into two categories: class components and class components
The class 1 components
Class components are state and declaration cycles, inherited from Component and implemented in the Render method. Example: Implement a clock with the class component
import React, {Component} from 'react'
export default class ClassComponent extends Component{
constructor(props) {
super(props)
this.state = {
date: new Date(a)
}
}
ComponentDidMount () {
this.timer = setInterval((a)= > {
thisSetState ({
date: new Date(a)
})
},1000)
}
ComponentWillUnmount () {
cleanInterval(this.timer)
}
Render () {
const {date} = this.state
return (
<div>
<h3>ClassComponent</h3>
<p>{date.toLocaleString()}</p>
</div>
)
}
}
Copy the code
The update state cannot be changed directly. Instead, use this.setState. The setInterval above is cleared when the component is uninstalled.
2 the Function component
The Function component had no concept of state until hooks came along. React Hook is a new feature introduced after React 16.8. Components can be given the same ability to manage their state as class components.
import ClassComponent from './pages/classComponent.js'
function App(a){
return (
<div className="App">
<ClassComponent />
</div>
)
}
Copy the code
Use the Function component to implement a clock
import React, { useState, useEffect } from 'react'
export default FunctionComponent(props){
const [date, setState] = useState(new Date())
useEffect((a)= > {
// componentDidMount, componentDidUpdate, componentWillUnmount
const timer = setInterval((a)= > {
setState(new Date())
}, 1000)
// Clear it when uninstalling
return (a)= > cleanInterval(timer)
}, [])
UseEffect is executed multiple times, independent of any data, only once
return(
<div>
<h3>Function Component</h3>
<p>{date.toLocaleString()}</p>
</div>
)
}
Copy the code
UseState and useEffect belong to hooks. That will be explained later