This is my fourth day of the August Challenge

1. Event binding

  • React event binding syntax is similar to DOM event syntax
  • OnClick ={()=>{}}
  • Note: Events are named with a hump: for example, onMouseEnter, onFocus

Class component

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
class App extends React.Component{
   handelClick(){
     console.log("Click the event off.")}render(){
    return(
      <button onClick={()= >{this. HandelClick ()}} > click</button>
  )}
}
ReactDOM.render(<App/>.document.getElementById('root'))
Copy the code

Function component binding event

function App(){
  function handleClick(){
    console.log('Click event triggered')}return (
    <button onClick={handleClick}></button>)}Copy the code

2. Event object

  • You can get the event object as an argument to the event handler

  • Event objects in React are called synthetic Events (Objects)

  • Composite events: Compatible with all browsers without worrying about cross-browser compatibility

function App(){
  function handleClick(e){
    e.preventDefault()
    console.log('A tag is triggered')}return (
    <a href="http://www.baidu.com" onClick={handleClick}>baidu</a>)}Copy the code

3. Stateful components and stateless components

  • Stateless component: Function component

  • Stateful components: Class components

    State is data

  • Function components have no state of their own and are only responsible for data presentation (static)

  • The class component has its own state and is responsible for updating the UI to make the page “move” such as counting from 0 to 1

4. State and setState() in components

4.1 Use of State

  • State data is private data within a component and can only be used within the component
  • The value of state is an object, indicating that there can be more than one piece of data in a component
  • Get the state from this.state

State initialization method 1: constructor must be initialized, and super() must also be written

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class App extends React.Component {
  // Initialize the state
  constructor(){
    // There must be a requirement for es6 class
    super(a)this.state ={
      count : 0}}render(){
    return(
      <div>
        {this.state.count}
      </div>
    )
  }
}

ReactDOM.render(<App/>.document.getElementById('root'))
Copy the code

Method two: the simplified writing method is recommended

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class App extends React.Component {
  // Simplify syntax to initialize state
  state ={
    count : 10
  }
  render(){
    return(
      <div>
        {this.state.count}
      </div>
    )
  }
}

ReactDOM.render(<App/>.document.getElementById('root'))
Copy the code

4.2 setState() Modifies the state

  • The state is variable
  • Syntax: this.setstate ({data to be modified})
  • Note: Do not directly modify the value in state, this is an error!!
/ / right
this.setState({
	count:this.state.count+1
})
/ / error
this.state.count += 1
Copy the code
  • SetState () : 1. Changes state. 2

counter

 state ={
    count : 10.test : 2    // If the object has multiple variables, setState only needs to write the variable that is being modified
  }
  render(){
    return(
      <div>
        {this.state.count}
        <button onClick={()= >{
          this.setState({
            count:this.state.count + 1
          })
        }}>+1</button>
        {this.state.test}
      </div>)}Copy the code
  • Idea: Data-driven view

4.3 Extracting event handlers from JSX

  • JSX has too much JS logic code, it will be very confusing
  • Recommendation: Isolate the logic into a separate method to keep the JSX structure clear
class App extends React.Component {
  state ={
    count : 10.test : 2
  }
  // Event handler
 onIncrement(){
  // This cannot be found
   console.log(this."this") 
    this.setState({
      count:this.state.count + 1})}render(){
    return(
      <div>
        {this.state.count}
        <button onClick={this.onIncrement}>+ 1</button>
      </div>)}}Copy the code

  • Cause: The value of this in the event handler is undefined
  • Want: this to point to a component instance (this in the render method is both a component instance)

5. Event binding to this point

5.1 Arrow Function

  • Take advantage of the fact that the arrow function itself is not bound to this. It is determined by external circumstances

5.2 the Function. The prototype. The bind ()

  • This in the event handler is bound to the component instance using the bind method in ES5
class App extends React.Component {
  constructor(){
    super(a)/ / binding to bind
    this.onIncrement = this.onIncrement.bind(this)
  }
  state ={
    count : 10.test : 2
  }
  // Event handler
 onIncrement(){
  // This cannot be found
   console.log(this."this") 
    this.setState({
      count:this.state.count + 1})}render(){
    return(
      <div>
        {this.state.count}
        <button onClick={this.onIncrement}>+ 1</button>
      </div>)}}Copy the code

5.3 Class Instance Methods (recommended)

  • Class instance methods in the form of arrow functions
  • Note: This syntax is experimental, but can be used directly because of Babel

Change the onIncrement function to the arrow function

  // Event handler
 onIncrement = () = >{
    this.setState({
      count:this.state.count + 1})}Copy the code

6. Form processing

6.1 Controlled Components

  • Form elements in HTML are inputable, that is, have their own mutable state
  • Mutable state in React, on the other hand, is usually stored in state and can only be modified with the setState() method
  • React binds state to the value of the form element. The value of state controls the value of the form element
  • Controlled component: A form element whose value is controlled by React
<input type="text" value={this.state.txt}/>
Copy the code

Step: 1. Add a state in state as the value of the form element (control where the form element value comes from) 2. Bind the change event to the form element and set the value of the form element to the value of state (to control the change of the form element value).

<input type="text" value={this.state.txt} 
onChange={e= >this.setState({txt:e.target.value})}/>
Copy the code

Text box changes value

class App extends React.Component {
  state ={
    count : 10.test : 2
  }
  handleChange = e= >{
    this.setState({
      count:e.target.value
    })
  }
  render(){
    return(
      <div>
        <input value={this.state.count} onChange={this.handleChange}></input>
      </div>)}}Copy the code

Using the React plugin, we can see that the count value in state has changed.Example: Check boxes (operation Checked)

<input type="checkbox" checked={this.state.check} onChange={this.handleChecked}>
Copy the code
  • Multiple form element optimizations

Problem: Having a separate event handler for each form element is too cumbersome optimization: Using one event handler to process multiple form element steps:

- 1. Add a name attribute to the form element with the same name as state - 2. 3. In the change event handler, change the corresponding state by [name]Copy the code
class App extends React.Component {
  state ={
    txt : 10.check : 2
  }
  handleChange = e= >{
    // Get the current DOM object
    const target = e.target
    // Get the value by type
    const value = target.type === 'checkbox'? target.checked : target.value/ / get the name
    const name = target.name

    this.setState({
      [name]:value
    })
  }
  render(){
    return(
      <div>
        <input name="txt" value={this.state.txt} onChange={this.handleChange}></input>
        <input name="check" type="checkbox" checked={this.state.check} onChange={this.handleChange}></input>
      </div>)}}Copy the code

6.2 Uncontrolled Components

  • With ref, use the native DOM method to get form element values
  • Get the Dom or component

Create a ref object by calling the React. CreateRef () method

constructor(){
	super(a)this.txtRef = React.createRef()
}
Copy the code

2. Add the created REF object to the text box

<input type="text" ref={this.txtRef}/>
Copy the code

3. Obtain the value of the text box from the ref object

console.log(this.txtRef.current.value)
Copy the code
class App extends React.Component {
constructor(){
  super(a)/ / create the ref
  this.txtRef = React.createRef()
}
getTxt = () = >{
  console.log(this.txtRef.current.value)
}
  render(){
    return(
      <div>
        <input name="txt" ref={this.txtRef}></input>
        <button onClick={this.getTxt}>getTxt</button>
      </div>)}}Copy the code

Ok, because it’s manipulating the DOM. It goes against React’s thinking.