React learning notes 3 - three attributes of components state, props and refs

state

1. The direction of the method this in the class

  • this in constructor and render points to the instance object of the class component
  • Ordinary functions defined inside the class component, as the callback of onClick, are not called through an instance, but directly. By default, the local strict mode is enabled inside the class component, so this points to undefind

2. Point this inside the function defined inside the class component to the instance object of the class component

  • Using arrow function
  • In the constructor, change the function this point through bind, and assign a value to the new function of the instance object

3. Writing of initialization status

  • The initialization state is written in the constructor this state = {}
  • If the class component omits the constructor, the initialization state can also be written directly in the component with state = {}

4. Read status

  • this.state. Status name

5. Change status

  • this.setState()
  • It cannot be modified or updated directly

For the above knowledge points and detailed explanations, please refer to the following codes and notes

<head>
  <div id="test"></div>
</head>

//Introduce some react core libraries and babel
<script type="text/javascript"  src="..."></script>

<script type="text/babel">
 
 //1. Create a class component
  class Demo extends React.Component {
      constructor(props){
         super(props)
         this.state = { // Initialization status
           isHappy:true, 
           isWeather:true 
         }
         this.changeWeather= this.changeWeather.bind(this) 
         //There is no changeWeather method on the instance, but it can be accessed through the prototype object. Then, this function is changed through bind and assigned to changeWeather on the instance object
      }
      
     // If the class component omits the constructor, the initialization state can also be written directly in the component with state = {}
     // state = { 
     //    isHappy:true, 
     //    isWeather:true 
     //}
      
      click = () => { // Using arrow function
        this.setState({
          isHappy:!isHappy
        })
      }
      
      changeWeather(){
      //changeWeather is placed on the prototype object of the Demo for use by the instance
      //changeWeather is a callback to onClick, so it is not called through an instance, but directly
      //The method in the class has local strict mode on by default, so this of changeWeather points to undefind
        this.setState({
          isWeather:!isWeather
        })
      }
	  render() {  
	    const {isHappy,isWeather} = this.state
	    return (
	      <div>
	        <h2 onClick={this.click}>I'm very happy today{ isHappy ? 'happy' : 'Sad'}</h2>  
	        <h2 onClick={this.changeWeather}>Today's weather{ isWeather ? 'very good' : 'Very bad'}</h2>  
	      </div>
	    )
	  }
  } 
 //2. Render virtual DOM to page
 ReactDOM.render(<Demo/> ,document.getElementById('test'))
</ script>

props

1.props is generally used to transfer values from parent components to child components

  • The parent component passes the value to the child component through the tag attribute
  • Subcomponents can be accessed through this props. Attribute name fetching

2. The sub component needs to introduce the prop types plug-in to define props

  • Defines the type of props incoming value
  • Defines whether the incoming value of props must be passed
  • Defines the default format for props incoming values

3. Read props

  • this.props. Attribute name

4. Change the incoming props value

  • It cannot be modified directly in the subcomponent by "this.props. Property name ="
  • The modification method needs to be defined in the parent component and passed to the child component. The child component calls the modification method to get the modified value

For the above knowledge points and detailed explanations, please refer to the following codes and notes

<head>
  <div id="test"></div>
</head>

//Introduce some react core libraries and babel
<script type="text/javascript"  src="..."></script>
//Introducing prop types plug-in
<script type="text/javascript"  src="..."></script>

<script type="text/babel">
 
 //Parent component
  class Info extends React.Component {
      state = {
        infomation:[
         {name:'Zhang San',sex:'male'},
         {name:'Li Si',sex:'female'}
        ]
      }
	  render() {  
	    const {infomation} = this.state
	    return (
	      <div>
	         <Person info={infomation}></Person>
	      </div?
	    )
	  }
  } 
  
  //Subcomponents
  class Person extends React.Component {
      static propTypes = { //Defines the type of props. isRequired indicates whether it is required 
        info: PropTypes.Array.isRequired
      }
      static defaultProps = { //Define the default display data of info
        info:[{name:'xxx',sex:'xxx'}]
      }
	  render() { 
	    const {info} = this.props 
	    return (
	      <ul>
	        {info.map(item => {
	          return <li>{name}:{sex}</li>
	         })
	        }
	      </ul>
	    )
	  }
   } 
 //2. Render virtual DOM to page
 ReactDOM.render(<Person/> ,document.getElementById('test'))
</ script>

refs

1. Definitions

  • Tags in components can define ref s to represent themselves and obtain their node data

2. Type of ref

  • String ref; For example: "ref =" input1 "" (it is not recommended by the official. If the usage is large, there is an efficiency problem)
  • Callback function ref; For example: "ref = {C = > this. Input2 = C}" (it will be executed twice during the update process. The first time the parameter is null, and the second time the parameter DOM element will be passed in, but it doesn't matter. It is recommended)
  • createRef

(for the above knowledge points and detailed explanations, please refer to the following codes and notes)

String ref case component

<head>
  <div id="test"></div>
</head>

//Introduce some react core libraries and babel
<script type="text/javascript"  src="..."></script>

<script type="text/babel">
 
 //String ref case component
  class Demo extends React.Component {
      click = () => {
        console.log(this.refs.input1) //input node of real DOM
        const {input1} = this.refs
        alert(input1.value) //Pop up the contents of the input box
      }
        
	  render() {  
	    return(
	      <div>
	         <input ref="input1" type="text" placeholder="Click the button to prompt data">
	         <button onClick={this.click}>Click the button to display the data on the left</button>
	      </div>
	    )
	  }
  }  
 //Render virtual DOM to page
 ReactDOM.render(<Demo/> ,document.getElementById('test'))
</ script>

Callback function ref case component

 //Callback function ref case component
  ...
  class Demo1 extends React.Component {
      showData= () => {
        const {input2} = this
        alert(input2.value) //Pop up the contents of the input box
      }
      
      saveInput = (c)=> { 
       this.input3 = c
       console.log(this.input3,c) //input node of real DOM
       alert(this.input3.value) //Pop up the contents of the input box
      }
     
	  render() {  
	    return(
	      <div>    
	         {/*1.ref={c => {console.log(c)}} At this time, the printed c is the input node, and then assign the node to the new attribute input2 on this, so you can use this Input2 obtains its DOM node;
	            2.A new function instance will be created during each rendering, so React empties the old ref and sets it to new, so this method will be executed twice during the update process. The first time the parameter is null, and the second time the parameter DOM element will be passed in;
	            3.However, the above problems do not matter and are recommended*/}
	         <input ref={c => this.input2= c} onBlur={this.showData}  type="text" placeholder="Lost focus prompt data">
	         
	           {/*The above problem is avoided by defining the callback function of ref as the binding function of class*/}
	          <input ref={this.saveInput} onBlur={this.showData}  type="text" placeholder="Lost focus prompt data">
	      </div>
	    )
	  }
  } 
 
 //Render virtual DOM to page
 ReactDOM.render(<Demo1/> ,document.getElementById('test'))

createRef case component

  //createRef case component
  ...
  class Demo2 extends React.Component {
    //React. After the createref () call, you can return a container that is used to store the node identified by ref
    //The container is dedicated. Each node needs its own container. If too many nodes use fef, it will be cumbersome. But it is officially recommended
     myRef = React.createRef()
     myRef2 = React.createRef()
     
     click = () => {
        console.log(this.myRef.current) //input node of real DOM
        const {current} = this.myRef
        alert(current.value) //Pop up the contents of the input box
     }
     
     showData= () => {
        const {current} = this.myRef2
        alert(current.value) //Pop up the contents of the input box
    }
      
	 render() {  
	    return(
	      <div>    
	         <input ref={this.myRef} type="text" placeholder="Click the button to prompt data">
	         <button onClick={this.click}>Click the button to display the data on the left</button>
	         <input ref={this.myRef2} onBlur={this.showData}  type="text" placeholder="Lost focus prompt data">
	      </div>
	    )
	  }
  } 
 //Render virtual DOM to page
 ReactDOM.render(<Demo2/> ,document.getElementById('test'))

Keywords: React

Added by dwardio on Wed, 26 Jan 2022 11:32:46 +0200