1. Get the DOM element from React

Get DOM elements from class 1.1 components

【 createRef 】 
import Reatc,{Component,createRef} from 'react'

class App extends Components{
  constructor() {
      super(a);this.myref = createRef()this.myref = react.createref ()}render() {
    return (
    	<div onClick={this.handole} ref={this.myRef}>Get the DOM element</div>
    )
  }
  handole =() = >{
  	const text = this.myref.currentconsole.log(text)
  }
}
Copy the code

1.2 Get DOM elements in function components

【 useRef 】

import useRef from 'react'

function App() {
	const myRef = useRef(null)
  
  const hanole =() = >{
  	console.log(myRef.surrent)
  }
  return (
  	<button onClick={hanole}>Get the DOM element</button>)}Copy the code

1.3 Types of refs

  1. When the [ref] attribute is used on a component, its return value is also different from that of the class component. The return value of current is a component object, which can be used to directly call methods inside the child component to manipulate values, etc
import React,{Component} from 'react'

export default class Header extends Component{" son"render() {
    return (
    	<div>Child components</div>
    )
  }
  handole = () = >{
  	console.log('Parent component called me')}}export default class App extends Component {[father]constructor() {
      super(a);this.myRef = React.createRef()

  }
  render() {
    return (
      <div>
        <Header  ref={myRef}/>
        <button onClick={this.getChildern}>Invoke methods in child components</button>
      </div>
    )
  }
  getChildern = () = >{
  	console.log(this.myref.current. Handole) [current returns a component object, through which the method is called]}}Copy the code
  1. If the component currently using ref is a function component, the component object cannot be retrieved.

1.4 Ref is used in functional components (higher-order components) to be updated

2. Controlled forms and uncontrolled forms

  1. Controlled forms are recommended in React. The values of form elements are managed by React, and the contents of the form are stored in [state]. The values of form elements are obtained in state
  2. [Uncontrolled form], the form element data is managed by itself. The value of the form element is stored in the DOM, and dom elements need to be manipulated when obtaining the form element

2.1 Controlled Forms

2.1.1 Input Box

1.Unidirectional unbinding of dataimport React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	name: 'Form contents'
  }
  render() {
    <form>
    	<input value={this.state.name} />
    </form>}} the value of the input box cannot be changed. If you want to change the value, you need to use the [onChange] event.export derault class App extends Component {
	state = {
  	name: 'Form contents'
  }
	render() {
  	<form>
    	<input value={this.state.name} onChange={this.handole.bind(this,e)} />
    </form>
  }
	handole = (e) = > {
  	this.setState({
    	name: e.target.value})}} : e.target.value})}}Copy the code

2.1.2 Processing of multiple inputs

  1. In a component, and sometimes there will be a lot of input box, a development of time, can’t each input box to write a method, these methods are the same operation, you need to merge method, merged into a method, through dynamically setting the key value of the object, in each input box to set the name attribute value 】, concrete implementation is as follows
1.The first thing to do is to set the name value for the input field.import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	user: ' '.password: ' '.email: ' '
  }
  render() {
    <form>
      <input 
        value={this.state.user}
        name="user"
        onChange={this.handole.bind(this.e)}  />
      <input 
        value={this.state.password}
        name="password"
        onChange={this.handole.bind(this.e)} />
      <input 
        value={this.state.email}
        name="email"
        onChange={this.handole.bind(this.e)} />
    </form>
  }
	handole = (e) = >{get the name and value of each element from the event object and assign them separately]this.setState({[input name must be the same as state key]: e.target.name]:e.target.valur})}} [.setState({[input name must be the same as state key]:e.target.valur})}} [2.Method 2: Set directly on the element.export derault class App extends Component {
	state = {
  	name: 'Form contents'
  }
  render() {
    <form>
      <input
        value={this.state.name}
        onChange={e= > {this.setState({ name: e.target.name })} } />
    </form>}}Copy the code

2.1.3 The form is submitted by default

  1. The form will submit the form by default. You need to prevent the form from being submitted. If you need to submit the form, you can submit the form manually
import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	name: 'Form contents'
  }
  render()<form onSubmit={<form onSubmit={(e) = >{this.handoleSubmit(e)} }> 
      <input value={this.state.name} />
      <input type="submit" />
    </form>
  }
  handoleSubmit = (e) = >{ e.preventDefault(); Prevent default behavior}}Copy the code

2.1.4 Input details processing

Warning: You provided a `value` prop to a form field without an `onChange` handler. 
This will render a read-only field. If the field should be mutable use `defaultValue`.
Otherwise, set either `onChange` or `readOnly`.
Copy the code
  1. In React, the console will warn you if you’re using a form to display data without modifying it or doing anything else. In React, if you don’t set onChange, the react will assume that the input box is a display. If you don’t set onChange, the react will check the other boxes and warn you if nothing is set
【 解决Warning 】
import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	name: 'Form contents'
  }
  render() {
    <form>【 solution 1: readOnly 】 scenario, want to display the value of state, but do not want to give react management<input value={this.state.name} readOnly/>[Solution 2: defaultValue] scenario, input pointer to display state data, that is, read-only cannot write<input defaultValue={this.state.name} />
    </form>}}Copy the code

2.1.5 Drop-down list

import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	name: 'react'The value must be the same as the value}render() {
    <select value={this.state.name} onChange={(e}= >{this.setState({ name: e.target.value })}>
      <option value="react">react</option>   	
      <option value="vue">vue</option>
      <option value="ag">ag</option>
    </select>}}Copy the code

2.1.6 Single and Check Options

  1. [Controlled single selection]
import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	sex: 'male'
  }
   render() {
    <form>DefaultChecked is checked in react. The value returned by defaultChecked is Boolean and true is checked. To dynamically toggle radio buttons<input type="radio" name="sex" value="Male" defaultChecked={this.state.sex= ='male'} / >Male [The default value in state will be changed later to achieve dynamic switching]<input type="radio" name="sex" value="Female" defaultChecked={this.state.sex= ='woman'} / >female</form>}}Copy the code
  1. [Controlled check]
import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	name: 'Form contents'
  }
	student = [ // The emulated backend returns data for the checkbox
  	{
      id: 0.name: 'vue'.isChecked: true
    },
    {
      id: 2.name: 'react'.isChecked: false
    },
    {
      id: 3.name: 'angle'.isChecked: false}]render() {
    <form onSubmit={e= >this.submit(e)}>
      {
      	this.student.map((item,index) => {
          return (
            <label key={item.id} htmlFor="FormChec">
            <input 
                className="FormChec"
                type="checkbox"
                defaultChecked={item.isChecked}
                onChange={(e)= >{this.handole(index,e)}} />{item.name}</label>)})}</form>
  }
	handole = (index,e) = >{【 Modify status value 】this.student[index].isChecked = e.target.checked
  }
  submit =(ev) = >{[submit form] ev.preventdefault (); [Click submit button, need to get the data you want, use variables for storage]let prop = this.student.filter(item= > item.isChecked).map(item= >Item. id) [merge the extracted data with the data inside the previous state, and return the final processing result to the server.] this.state,prop } } }Copy the code

2.2 Uncontrolled forms to be updated

3. Unidirectional data flow

  1. The design principle of single data flow requires us to define the data that needs to be shared between different components on the top layer, inside the parent component, and there is nesting relationship between components, one layer of components.
import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	name: 'Sharing data'
  }
	render() {
		return (
    	<div>
      	<Header { . this.state} / >
      </div>)}}export default function Header(props) {【props receive data from the upper component 】return (
  	<div>
    	<Main {. props} / >
    </div>)}export default function Main(props) {【props receive data from the upper component 】return (
  	<div>
    	<span>{ props.name }</span>
    </div>)}Copy the code

3.1 How can I Modify a Single Data Flow

  1. Individual data flow modifications do more than just pass data to child components; sometimes, child components trigger operations to change the top-level data. The child component can change the data by calling methods passed by the parent component.
1.The parent defines a method to change state, passing the method to the component, which receives the event, calls, and passes the value it wants to change.import React,{Component} from 'react'

export derault class App extends Component {
	state = {
  	name: 'Sharing data'
  }
   render() {
     return (
    	<div>
      	<Header { . this.state} / >
      </div>
    )
  }
	handole =(value) = >{[Receive value passed by component]this.setState({
    	name: value.name
    })
  }
}

export default function Main(props) {the lowest level component modifies the data of the top level component.return (
  	<div>
    	<span>{ props.name }</span>
      <button onClick={()= >{props. Handole ({name:' the underlying component modified the data of the top component '})}}> Modify the data of the top component</button>
    </div>)}Copy the code

3.2 Characteristics of single data flow

  1. Data flow principle: Pass data from the top parent component to the child component.

  2. When using monomial data flows, the shared data needs to be defined within the top-level parent component

  3. The child component can change the data by calling methods passed by the parent component.

  4. When the data changes, it is re-rendered onto the DOM element