Two ways to create a class component
1. The ES5 way
import React form 'react'
const A = React.createClass({render(){<div>hi</div>}})
export default A
Copy the code
This approach is used because ES5 does not support classes
2. ES6 way
import React form 'react'
class B extends React.Component{
constructor(props){
super(props)
// ...
}
render(){
return(<div>hi</div>)
}
}
export default B
Copy the code
Second, the Props
1. Initialization
Class B extends react.component{constructor(props){super(props) // super(props),this. Props is the address of the external object / /... } render(){ //... }}Copy the code
2. Read
Class B extends react.component{constructor(props){super(props) // super(props),this. Props is the address of the external object / /... } render(){ <div onClick={this.props.add}> {this.props.name} </div> } }Copy the code
Read from this.props. XXX
3. Write
Don’t write, and don’t ever try to rewrite props
4. The role of Props
(1) Used to receive external data
External data can only be read, not written, and is passed by the parent component
(2) Receiving external functions
This function is called when appropriate, provided by the parent component
Third, the State
1. Initialization
class B extends React.Component{ constructor(props){ super(props) this.state = { n:1, m:2 } } render(){ //... }}Copy the code
2. Read
Write this.state.n inside the component
3. Write
Call this.setState(argument 1, argument 2), argument 2 is a function that will be called after the callback succeeds.
Note: setState is an asynchronous operation and does not immediately change this.state. SetState automatically merges the first layer of data in state
4. Bind events
<button onclick={()=> this.addn ()}> n+1 </button> <button onclick={this.addn. Bind (this)}> n+1 </button <button onclick={this.addN}> n+1 </button Button.onclick.call (); this === null; this = undefind; For nudefind, it becomes window. // The recommended way to write this is to use the arrow function addN =()=> this.setState().Copy the code