React practice is essential to note (5) - React and DOM

  React to achieve a set of DOM browser-independent system, including elements rendering, node query, event handling mechanisms.

A, ReactDOM

  React v0.14 from the beginning, will be associated with the official release from DOM React operation, the composition of the individual react-dom library, so that more terminals compatible React. After the introduction react-dom library, you can call a global object: ReactDOM, although the object has been used several times in the previous chapters, but did not give too many explanations, this section focuses on its done.

  ReactDOM contains only unmountComponentAtNode (), findDOMNode (), createPortal () and render () method of the few and several other, wherein the first two described in the render () function, and the first four of the mentioned removing the mounted assembly with the DOM unmountComponentAtNode () method. Next we will explain the remaining two methods.

1) findDOMNode ()

  When the assembly is rendered to the page in real DOM can be obtained by generating the DOM element findDOMNode () method, and then be able to complete such as reading, calculate the size and other operations.

  Note that, findDOMNode () Gets assembly mounted only, and not for the assembly function. In the life cycle of components, which can only exist in componentDidMount () and componentDidUpdate () two callback, call elsewhere will throw an error, as shown below.

class Btn extends React.Component {
  render() {
    ReactDOM.findDOMNode(this);        //抛出错误  
    return <button>提交</button>;
  }
  componentDidMount() {
    ReactDOM.findDOMNode(this);        //<button>提交</button>
  }
}

  In the above example, this point is Btn component instance, after this pass findDOMNode () method to obtain a <button> element. One thing to note, if render components () return null or false, then findDOMNode () will return null.

2)createPortal()

  In React v16, add the Portal characteristics, to allow the component rendering DOM nodes other than the parent components. This feature applies to scenarios need to jump out of a container, such as creating custom pages bomb inside the box.

  React use Portal characteristics, the need to call a new method on the ReactDOM: createPortal (). This method can receive two parameters, the first child is rendered React elements, such as strings, React other elements of the array; second DOM element, which is mounted to the container. Specific use for this method may be reference to the following examples.

class Btn extends React.Component {
  render() {
    return ReactDOM.createPortal(this.props.children, document.body);
  }
}
ReactDOM.render(<Btn><p>按钮</p></Btn>, document.getElementById("container"));

  In the above call ReactDOM.createPortal render () method (), such that <p> element eventually mounted to the <body> element, the id attribute is not "container" element.

Two, Refs

  Refs an access method, which can be read by the render () method of the generated DOM component instance and elements used to focus the processing elements, trigger the animation, DOM integrate third party libraries. Note that in the life cycle of the assembly, let Refs effective, have to put it componentDidMount () and componentDidUpdate () callback function in the job two. While Refs give certain scenes to bring convenience, but it destroys the typical data stream React to pass data through the props, so try to avoid the use of Refs.

  If you are using Refs functions, then you have to set the ref attribute React element, its value can be an object, the callback function and value of these three strings, the following will explain the ref attribute, respectively.

1) Objects

  Here the object is to return the value React.createRef () method, comprising a current attribute, and the attribute points to the DOM element or component instance is to be read. The following example shows the properties and React.createRef ref mating process () method.

class Btn extends React.Component {
  constructor(props) {
    super(props);
    this.myBtn = React.createRef();
  }
  render() {
    return <button ref={this.myBtn}>提交</button>;
  }
  componentDidMount() {
    let btn = this.myBtn.current;
    console.log(btn);         //<button>提交</button>
  }
}

  First calls the constructor assembly React.createRef (); Return Value then assigned this.myBtn, so that we can use the object at an arbitrary position inside the assembly; then let this.myBtn be <button> element ref value of the property; and finally able to successfully read componentDidMount () to the current value of property, to complete a type of access Refs.

2) callback function

  The callback function to receive a parameter (code shown below), when the assembly is mounted, is a component instance or a DOM element parameter; when the assembly is unloaded, the parameter is null.

class Btn extends React.Component {
  render() {
    return (
      <button ref={btn => { this.myBtn = btn }}>提交</button>
    );
  }
  componentDidMount() {
    let btn = this.myBtn;
    console.log(btn);           //<button>提交</button>
  }
}

  The biggest difference with the former use is to remove the dependence on React.createRef () method, which is directly assigned to this.myBtn parameter in the callback function, you can get the expected results, you do not have to call a current property.

3) string

  Ref attribute values ​​may also be a string, for example, the following code "myBtn", can access to the desired component instance or a DOM element by this.refs.myBtn.

class Btn extends React.Component {
  render() {
    return <button ref="myBtn">提交</button>;
  }
  componentDidMount() {
    let btn = this.refs.myBtn;
    console.log(btn);           //<button>提交</button>
  }
}

  However, officials have not recommended such an approach, and it is possible in a future version will be removed, it is recommended to switch mode callback function.

4) Use Scene

  ref attribute only can be applied as the DOM elements as in the previous example, also using the ref attribute class in the assembly, as shown in the following code.

class Btn extends React.Component {
  render() {
    return <button>提交</button>;
  }
}
class Container extends React.Component {
  render() {
    return <Btn ref={btn => { this.myBtn = btn }}>提交</Btn>;
  }
  componentDidMount() {
    let btn = this.myBtn;
    console.log(btn);           //Btn组件的实例
  }
}

  Container Btn is the parent component, in which render () method, the callback function assigned to the component instance Btn this.myBtn.

  Since there is no instance of the component functions, and therefore can not be added thereto ref attribute.

DOM element 5) subassembly

  In the parent component, if you want to access a DOM element sub-components, then the ref attribute alone can not be achieved because the ref attribute resulting only instance of sub-assemblies. However, there may be an indirect way to achieve this demand, and that the ref attribute ReactDOM.findDOMNode () with the use. Apply the following usage scene in a Container and Btn two components, only the modified portion of the code is listed, the rest have been omitted.

class Container extends React.Component {
  componentDidMount() {
    let btn = this.myBtn;
    let dom = ReactDOM.findDOMNode(btn);
    console.log(dom);         //<button>提交</button>
  }
}

  In componentDidMount () method is called once ReactDOM.findDOMNode (), thereby obtaining the DOM element subassembly has.

三、Fragments

  JSX structure has a limit, that is to be wrapped with an element in the outermost layer, even if it is a redundant element, they have to add. For example, a <ul> element to mount a set of elements of the set, as shown below.

class Btns extends React.Component {
  render() {
    return (
      <div>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </div>
    );
  }
}

  Render on the page DOM look like the following, where <div> element here is not useful.

<ul id="container">
  <div>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </div>
</ul>

  In order to avoid such a meaningless output, React introduced Fragments, whose structure is shown below code. Simply start and end tags outermost <div> elements were changed to <> and </>, do not add extra elements in the DOM.

class Btns extends React.Component {
  render() {
    return (
      <>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </>
    );
  }
}

1)React.Fragment

  <> And </> will eventually be compiled into the start and end tags React.Fragment components, that is, the former is the syntax sugar. The following code example and on a Fragments are equivalent.

class Btns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </React.Fragment>
    );
  }
}

  If you want to add Keys identified as Fragments (that is defined for key attributes), you can only use React.Fragment components wrap child elements. Note, key is the only available property React.Fragment components.

 

Guess you like

Origin www.cnblogs.com/strick/p/10593862.html