search
HomeWeb Front-endJS TutorialWhat are the functions of react? Detailed analysis of react function (with examples)

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]
);

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;)
);

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

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;)
);

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;)
);

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;)
);

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 id="Comments">Comments</h1>
        <CommentList data={this.state.data} />
      </p>
    );
  }
});

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()

In addition, there are two special status processing functions:

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

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
);

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");
}

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
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
The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft