Table of Contents
Core function 1:render
Core function 2: React.createClass
Component state
Life cycle of components
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)

Sep 11, 2018 pm 03:55 PM
javascript react

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles