Home > Web Front-end > JS Tutorial > body text

How to use react? Detailed explanation of the usage of react (with examples included)

寻∝梦
Release: 2018-09-11 16:10:13
Original
3150 people have browsed it

This article mainly introduces the use of react. Interested students can click in to see about the use of react. Let us take a look at the content of this article

1. React Props

1. Use props

The main difference between state and props is that props are immutable, while state can be modified based on user interaction to change. This is why some container components need to define state to update and modify data. Subcomponents can only pass data through props.

The name attribute in the instance is obtained through this.props.name.

2. Default props

You can set default values ​​for props through the getDefaultProps() method.

2. Component API

1. Set state: setState

setState(objectnextState[, function callback])

( 1) Parameter description:

nextState, the new state to be set, which will be merged with the current state

callback, optional parameters, callback function. This function will be called after setState is set successfully and the component is re-rendered.

Merge nextState and current state, and re-render the component. setState is the main method to trigger UI updates in React event handling functions and request callback functions.

(2) About setStaate

The state cannot be modified through this.state inside the component, because the state will be replaced after calling setState().

setState() does not immediately change this.state, but creates a state that is about to be processed. setState() is not necessarily synchronous. In order to improve performance, React will perform state and DOM rendering in batches.

setState() will always trigger a component redraw unless some conditional rendering logic is implemented in shouldComponentUpdate().

2. Replacement state: replaceState

replaceState(object nextState[, functioncallback])

nextState, the new state to be set, This state replaces the current state.

callback, optional parameters, callback function. This function will be called after replaceState is set successfully and the component is re-rendered.

The replaceState() method is similar to setState(), but the method will only retain the state in nextState, and the original state that is not in nextState will be deleted.

3.        Set properties: setProps

setProps(object nextProps[, functioncallback])

nextProps, to be set New attribute, this state will be merged with the current props

callback, optional parameters, callback function. This function will be called after setProps is set successfully and the component is re-rendered.

Set component properties and re-render the component.

4. Replacement properties: replaceProps

replaceProps(object nextProps[, functioncallback])

nextProps, to be set A new property that replaces the current props.

callback, optional parameters, callback function. This function will be called after replaceProps is set successfully and the component is re-rendered.

replaceProps()The method is similar to setProps, but it will delete the original props

5.            Force update: forceUpdate

forceUpdate([function callback])

The forceUpdate() method will cause the component to call its own render() method to re-render the component. Components also call their own render(). However, when the component is re-rendered, this.props and this.state will still be read. If the state has not changed, React will only update the DOM.

The forceUpdate() method is suitable for redrawing components other than this.props and this.state (for example: after modifying this.state). This method is used to notify React that render needs to be called. ()

6. Get DOM node: findDOMNode

DOMElement findDOMNode()

Return value: DOM element DOMElement

If the component has been mounted in the DOM, this method returns the corresponding local browser DOM element. When render returns null or false, this.findDOMNode() will also return null. This method is useful when reading values ​​from the DOM, such as getting the value of a form field and doing some DOM operations.

7. Determine the component mounting status: isMounted

bool isMounted()

Return value: true or false, indicating whether the component has been mounted in the DOM (if you want to know more, go to the React Reference Manual column on the PHP Chinese website to learn)

isMounted( ) method is used to determine whether the component has been mounted in the DOM. This method can be used to ensure that the calls to setState() and forceUpdate() in asynchronous scenarios will not go wrong.

3. React component life cycle

1. The component life cycle can be divided into three states:

Mounting: Real DOM has been inserted

Updating: Being re-rendered

Unmounting: Moved out of the real DOM

2. The life cycle methods are:

1) componentWillMount is called before rendering, both on the client and on the server.

2) componentDidMount: Called after the first rendering, only on the client side. Afterwards, the component has generated the corresponding DOM structure, which can be accessed through this.getDOMNode(). If you want to use it with other JavaScript frameworks, you can call setTimeout, setInterval or send AJAX requests and other operations in this method (to prevent foreign operations from blocking the UI).

3) componentWillReceiveProps is called when the component receives a new prop (after update). This method will not be called when initializing render.

4) shouldComponentUpdate Returns a Boolean value. Called when the component receives new props or state. Not called during initialization or when using forceUpdate.
Can be used when you confirm that you do not need to update components.

5) componentWillUpdate is called when the component receives new props or state but has not yet rendered. Will not be called during initialization.

6) componentDidUpdate Called immediately after the component completes the update. Will not be called during initialization.

7) componentWillUnmount is called immediately when the component is removed from the DOM.

4.React forms and events

Example 1: We can update state when the input box value changes . We can use the onChange event to monitor input changes and modify the state.

5. React Refs

1. Use method

to bind a ref attribute to the return of render Value:

##

In other codes, obtain the support instance through this.refs :

var input = this.refs.myInput;

var inputValue = input.value;

var inputRect = input.getBoundingClientRect();

2. Example

The input box gets focus after the child clicks the button.

v

ar MyComponent = React.createClass({
      handleClick: function() {
        // 使用原生的 DOM API 获取焦点
        this.refs.myInput.focus();
      },
      render: function() {
        // 当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refs
        return (
          <p>
            <input type="text"ref="myInput" />
            <input
              type="button"
              value="点我输入框获取焦点"
              onClick={this.handleClick}
            />
          </p>
        );
      }
    });
 
    ReactDOM.render(
      <MyComponent />,
      document.getElementById(&#39;example&#39;)
    );
Copy after login

This article ends here (if you want to see more, go to the PHP Chinese website

React User Manual column to learn), there are If you have any questions, you can leave a message below.

The above is the detailed content of How to use react? Detailed explanation of the usage of react (with examples included). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!