DOM operation implementation in react

DOM operation implementation in react

Previous words

In some cases it is necessary to force modifications to children outside of the typical data flow. The child to be modified can be a React component instance or a DOM element. At this time, refs are used to operate DOM

Usage scenarios

Here are a few situations where refs are suitable:

1. Handle focus, text selection, or media controls

2. Trigger forced animation

3. Integrate third-party DOM libraries

Avoid using refs if you can do it declaratively.

[Note] Do not expose the open() and close() methods directly on the Dialog component. It is better to pass the isOpen property.

ref

React supports adding special attributes to any component. The ref attribute accepts a callback function that is executed immediately when the component is mounted or unmounted.

[Note] Get the ref after the component is mounted. It cannot be obtained in componentWillMount or the first render, but can be obtained in componentDidMount

HTML elements

When adding a ref attribute to an HTML element, the ref callback receives the underlying DOM element as a parameter.

React components pass the DOM element into the ref callback function when they are loaded, and pass null when they are unloaded. The ref callback is executed before the componentDidMount or componentDidUpdate lifecycle callbacks.

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }
  focus() {
    this.textInput.focus();
  }
  render() {
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

A shorter way to write it is as follows

ref={input => this.textInput = input}

Class Component

When the ref attribute is used for a custom component declared using a class, the ref callback receives the loaded React instance.

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
    this.textInput.focusTextInput();
  }

  render() {
    return (
      <CustomTextInput
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

[Note] This method is only valid for CustomTextInput declared in class

Functional Components

You cannot use the ref attribute on functional components because they do not have instances.

[Exposing DOM nodes to parent components]

Expose a special attribute on child nodes. The child node will get a function attribute, which will be attached to the DOM node as a ref attribute. This allows the parent to pass a ref back to the child's DOM node via the middleware

This method is applicable to both class components and functional components.

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

class Parent extends React.Component {
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

In the example above, Parent passes its ref callback to CustomTextInput as a special inputRef, which CustomTextInput then passes to the <input> via the ref attribute. Finally, this.inputElement in Parent will be set to the DOM node corresponding to the <input> element in CustomTextInput

Uncontrolled components

To write an uncontrolled component, instead of writing event handlers for each state update, you can use a ref to get the form value from the DOM

[Note] You can get the DOM value through e.target.value without binding react

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={(input) => this.input = input} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Since uncontrolled components store real data in the DOM, it is easier to integrate React and non-React code at the same time when using uncontrolled components.

【default value】

During the React lifecycle, the value attribute on the form element will override the value in the DOM. When using an uncontrolled component, you usually want React to assign an initial value to it, but no longer control subsequent updates. To solve this problem, you can specify a defaultValue attribute instead of a value.

render() {
  return (
    <form onSubmit={this.handleSubmit}>
      <label>
        Name:
        <input
          defaultValue="Bob"
          type="text"
          ref={(input) => this.input = input} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
}

Similarly, <input type="checkbox"> and <input type="radio"> support defaultChecked, <select> and <textarea> support defaultValue

ReactDOM

The react-dom package provides methods for the DOM that can be called from the top-level scope of your application, and can also be used as an exit point outside the React model if needed. But most components should not need to use this package

render()
unmountComponentAtNode()
findDOMNode()

【render()】

ReactDOM.render(
  element,
  container,
  [callback]
)

Renders a React element, appended to the DOM element in the provided container, and returns a reference to the component (or null for stateless components).

If the React element has been rendered into a container before, this code will perform an update and only change the DOM elements necessary to reflect the element's latest state.

【unmountComponentAtNode()】

ReactDOM.unmountComponentAtNode(container)
Removes a mounted React component from the DOM element, clearing its event handlers and state. If no components are mounted in the container, this function will do nothing. Returns true when a component is uninstalled, and false when no component is available to uninstall

[findDOMNode()]

ReactDOM.findDOMNode(component)
If this component has been mounted into the DOM, the function will return the corresponding DOM element generated in the browser. This function is very useful when you need to read values ​​from the DOM, such as form values, or calculate the size of DOM elements. In most cases, you can add a reference to a DOM node and avoid using the findDOMNode function altogether. When render returns null or false, findDOMNode also returns null

New ref

Before version 16.3, React had two ways to provide refs: string and callback. Because the string method has some problems, the official recommendation is to use callbacks to use refs. The createRef API introduced now is officially said to be a zero-defect way to use ref, and the callback method can also give way

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

Then use the current attribute to get the current element

this.myRef.current

Typical applications are shown below

  constructor(props){
    super(props)
    this.Mask = React.createRef()
    this.MenuList = React.createRef()
  }
  handleClick = () => {
    ReactDOM.findDOMNode(this.MenuList.current).classList.toggle('transform-zero')
    ReactDOM.findDOMNode(this.Mask.current).classList.toggle('mask-show')
  }

[Note] The interface exposed by elements styled with styledComponents is innerRef, not ref

<Wrap innerRef={this.itemRef}>

This is the end of this article about the implementation of DOM operations in react. For more relevant react DOM operations, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of virtual DOM and diff algorithm in react
  • Detailed explanation of operating virtual DOM to simulate react view rendering
  • A brief discussion on the biggest highlight of React: Virtual DOM
  • An example of React operating the real DOM to achieve dynamic bottom absorption
  • How to render components to specified DOM nodes in React

<<:  Create a new user in Linux and grant permissions to the specified directory

>>:  Does MySql need to commit?

Recommend

mysql 5.7.23 winx64 decompression version installation tutorial

Detailed installation tutorial of mysql-5.7.23-wi...

Causes and solutions for MySQL too many connections error

Table of contents Brief summary At noon today, th...

How to add file prefixes in batches in Linux

You need to add "gt_" in front of the f...

MySQL 5.7.21 installation and configuration method graphic tutorial (window)

Install mysql5.7.21 in the window environment. Th...

Mysql experiment: using explain to analyze the trend of indexes

Overview Indexing is a skill that must be mastere...

Markup language - specify CSS styles for text

Click here to return to the 123WORDPRESS.COM HTML ...

Summary of Linux command methods to view used commands

There are many commands used in the system, so ho...

CSS sets Overflow to hide the scroll bar while allowing scrolling

CSS sets Overflow to hide the scroll bar while al...

How to use cursor triggers in MySQL

cursor The set of rows returned by the select que...

MySQL green decompression version installation and configuration steps

Steps: 1. Install MySQL database 1. Download the ...

MySQL full-text search Chinese solution and example code

MySQL full text search Chinese solution Recently,...

CSS 3.0 text hover jump special effects code

Here is a text hovering and jumping effect implem...

How to keep running after exiting Docker container

Phenomenon: Run an image, for example, ubuntu14.0...