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

Detailed explanation of the entry-level use of MySql stored procedure parameters

Use of stored procedure in parameters IN paramete...

Detailed explanation of Vue save automatic formatting line break

I searched for many ways to change it online but ...

CSS text alignment implementation code

When making forms, we often encounter the situati...

React new version life cycle hook function and usage detailed explanation

Compared with the old life cycle Three hooks are ...

Use of filter() array filter in JS

Table of contents 1. Introduction 2. Introduction...

Solve the problem of not finding NULL from set operation to mysql not like

An interesting discovery: There is a table with a...

How to implement MySQL bidirectional backup

MySQL bidirectional backup is also called master-...

JavaScript Dom Object Operations

Table of contents 1. Core 1. Get the Dom node 2. ...

Detailed explanation of formatting numbers in MySQL

Recently, due to work needs, I need to format num...

Detailed explanation of common MySQL operation commands in Linux terminal

Serve: # chkconfig --list List all system service...

Example of how to create a database name with special characters in MySQL

Preface This article explains how to create a dat...

Detailed explanation of MYSQL database table structure optimization method

This article uses an example to illustrate the me...

Detailed instructions for installing Jenkins on Ubuntu 16.04

1. Prerequisites JDK has been installed echo $PAT...

Examples of using the or statement in MySQL

1. The use of or syntax in MySQL, and the points ...

MySql index improves query speed common methods code examples

Use indexes to speed up queries 1. Introduction I...