Home > Web Front-end > JS Tutorial > What are the functions of react? Detailed analysis of react function (with examples)

What are the functions of react? Detailed analysis of react function (with examples)

寻∝梦
Release: 2018-09-11 15:55:13
Original
3167 people have browsed it

This article mainly talks about how to learn react. Now let’s take a look at the main content of the article

React is basically a JavaScript library.

It embodies the idea of ​​separation of front and back, transferring part of the work of assembling the page to the browser; unlike JSP files, the layout of the page and filling in data are sent to the browser after the server completes it. .

There are naturally many benefits to this: First of all, React encapsulates DOM&JavaScript into modules (components). These components are highly reusable. Not only that, components can also make testing and separation of concerns simple. . Secondly, when data changes, React can automatically update the user interface and only update the parts that need to be updated.

Core function 1:render

The function of this function is to provide a module, which is like a piece of Lego toy used to assemble the page.

Simple example: (The html code is given first, and the JSX code is given later. JSX means JavaScript XML)

<p id="container" class="firstContainer">
  <p>replaced</p>
</p>/*************************************************/ReactDOM.render(
    <p>Hello, world!</p>,
    document.getElementsByClassName(&#39;firstContainer&#39;)[0]
);
Copy after login

You can see the content of p with class firstContainer was replaced by the code we wrote in render: hello world!

In addition document.getElementsByClassName('firstContainer')[0] can be replaced with any native JavaScript to get ** a single one (must be a Node, so if you use a method like document.getElementsByClassName you must add [n]) **DOM element methods: document.getElementById or document.getElementsByTagName, etc. are all acceptable.

For a more complex example, we can expand the <p>Hello, world!</p> here.

<p id="container" class="firstContainer">
  <p>replaced</p>
</p>/*************************************************/var name = "Emily";
ReactDOM.render(
  <p>
  {
    (function(){        return <p>Hello, {name}!</p>
    })()
  }
  </p>,
  document.getElementById(&#39;container&#39;)
);
Copy after login

We can see the magic of JSX syntax. In the code, JS and DOM can be said to be mixed together. The basic syntax rules of JSX: when encountering HTML tags (starting with <), use HTML rules to parse; when encountering code blocks (starting with {), use JavaScript rules to parse.

Core function 2: React.createClass

This function allows us to define the required components ourselves. The defined components can be used directly in the render function as tags like p.

A simple chestnut:

<p id="container" class="firstContainer">
  <p>replaced</p>
</p>/*************************************************/var HelloWorldBox = React.createClass({
  render: function() {    return (
      <p className="helloWorldBox">
        Hello, world! I am a helloWorldBox.
      </p>
    );
  }
});
ReactDOM.render(
  <HelloWorldBox />,
  document.getElementById(&#39;container&#39;)
);
Copy after login

In this chestnut, HelloWorldBox is the simplest component.

We can also get more information about this component. For example, using props

(example from React official website)

<p id="container" class="firstContainer">
  <p>replaced</p>
</p>/*************************************************/var Comment = React.createClass({
  render: function() {    return (
      <p className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        {this.props.children}
      </p>
    );
  }
});var CommentList = React.createClass({
  render: function() {    return (
      <p className="commentList">
        <Comment author="Pete Hunt">This is one comment</Comment>
        <Comment author="Jordan Walke">This is *another* comment</Comment>
      </p>
    );
  }
});
ReactDOM.render(
  <CommentList />,
  document.getElementById(&#39;container&#39;)
);
Copy after login

In this example, we use the React.createClass method to create two components. We can see that in the component CommentList, Nested Comment: In other words, CommentList is composed of multiple Comments. We define an attribute for Comment in CommentList: author. Then, in the Comment component, you can read this property through {this.props.author}, and through {this.props.children}, you can read the child nodes of this component.

Access external data:

<p id="container" class="firstContainer">
  <p>replaced</p>
</p>/*************************************************/var Comment = React.createClass({
  render: function() {    return (
      <p className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        {this.props.children}
      </p>
    );
  }
});var names = [&#39;Alice&#39;, &#39;Emily&#39;, &#39;Kate&#39;];
ReactDOM.render(
  <p>
  {
    names.map(function (name) {      return <Comment author={name}>is an author~</Comment>
    })
  }
  </p>,
  document.getElementById(&#39;container&#39;)
);
Copy after login

Here, the array names is external data. We embed these data into the DOM of the web page by creating components.

Component state

Each component has a property: state. Developers can change the state of the component by calling this.setState(). When the state is updated, the component will re-render itself. Both state and props are characteristics of a component, but the difference is that props are unchanged, but state can be changed.

getInitialState() can set the initialization state of the component. This function is only executed once in the component's life cycle.

Update status:

Note: The componentDidMount function is the life cycle function of the component. It is a method that React automatically calls when the component is rendered. It will be discussed in detail later.

var CommentBox = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    $.ajax({
      url: this.props.url,
      dataType: &#39;json&#39;,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (
      <p className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data} />
      </p>
    );
  }
});
Copy after login

In this chestnut, we obtain data through ajax and set the obtained data to this.state.data through the function this.setState. Then, in the CommentList, set data={this.state.data} to display the data obtained from the server. (If you want to learn more, go to the PHP Chinese website React Reference Manual column to learn)

Life cycle of components

The life cycle of components is divided into the following three types:

  1. Mounting: The real DOM has been inserted

  2. Updating: Being re-rendered

  3. Unmounting: Already Move out of the real DOM

In the component's life cycle, life cycle functions will be automatically called. They are:

componentWillMount()componentDidMount()componentWillUpdate(object nextProps, object nextState)componentDidUpdate(object prevProps, object prevState)componentWillUnmount()
Copy after login

In addition, there are two special status processing functions:

componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用
Copy after login

The following chestnut comes from Ruan Yifeng’s blog:

var Hello = React.createClass({
  getInitialState: function () {
    return {
      opacity: 1.0
    };
  },
  componentDidMount: function () {
    this.timer = setInterval(function () {
      var opacity = this.state.opacity;
      opacity -= .05;      if (opacity < 0.1) {
        opacity = 1.0;
      }      this.setState({
        opacity: opacity
      });
    }.bind(this), 100);
  },
 render: function () {
    return (
      <p style={{opacity: this.state.opacity}}>
        Hello {this.props.name}
      </p>
    );
  }
});
ReactDOM.render(
  <Hello name="world"/>,
  document.body
);
Copy after login

The componentDidMount function is in It is called after the component is inserted into the real DOM. In this function, we set a timer to change the transparency every 100 milliseconds until the component is completely transparent, and then set the transparency to 1 (the initial transparency is set to 1). In this way, this component party is constantly being rendered. In this way, we get a flashing hello world string on the page. If we write the function:

componentDidUpdate:function(){
    console.log("did update");
}
Copy after login

we can see continuous output on the console.

React is basically a JavaScript library.

It embodies the idea of ​​separation of front and back, transferring part of the work of assembling the page to the browser; unlike JSP files, the layout of the page and filling in data are sent to the browser after the server completes it. .

There are naturally many benefits to this: First of all, React encapsulates DOM&JavaScript into modules (components). These components are highly reusable. Not only that, components can also make testing and separation of concerns simple. . Secondly, when data changes, React can automatically update the user interface and only update the parts that need to be updated.

This article ends here (if you want to see more, go to the PHP Chinese website React User Manual column to learn). If you have any questions, you can leave a message below.

The above is the detailed content of What are the functions of react? Detailed analysis of react function (with examples). 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