国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

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

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>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):已加載組件收到新的參數(shù)時調(diào)用shouldComponentUpdate(object nextProps, object nextState):組件判斷是否重新渲染時調(diào)用

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

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.

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.

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React's Ecosystem: Libraries, Tools, and Best Practices React's Ecosystem: Libraries, Tools, and Best Practices Apr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

Netflix's Frontend: Examples and Applications of React (or Vue) Netflix's Frontend: Examples and Applications of React (or Vue) Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

React: The Power of a JavaScript Library for Web Development React: The Power of a JavaScript Library for Web Development Apr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

See all articles