Home Web Front-end JS Tutorial Introduction to the method of creating React Element (detailed process)

Introduction to the method of creating React Element (detailed process)

Oct 29, 2018 pm 03:40 PM
javascript

This article brings you an introduction to the method of creating React Element (detailed process). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In the previous chapter, we used the create-react-app tool to build a development environment based on react. From this chapter, we officially start the react framework study.

Open the my-app project and find the src/index.js file. As we mentioned in the previous chapter, this file is the entrance to the entire application. When the page is refreshed, this file will be actively loaded. Then here we directly delete other files in this directory and save only index.js. Then delete the default code in this file and call the console.log("in") method to output on the console.

Use the yarn start command to start the project, open the browser developer tools, and you can see that the console is printed successfully. In the development environment built using scaffolding tools, the hot loading function has been implemented. That is to say, after we complete the modification of the js code, we no longer need to refresh frequently to view the effect of the page. After each modification is saved, browse The server will automatically refresh the page. For example, here, I slightly changed the string output here, and then saved it. You can see that the console has output the newly modified string.

React Element

Okay, back to the knowledge point of the react framework, we know that a page is composed of many node elements, for example, h1 element, p element, ul element and so on. In fact, in react, the smallest component unit is also an element, but we call it react element. So, how do we create a react element?

For example, here I need to display an h1 element on the page, which contains a Hello World string. Then first I need to create such a react element.

In the react framework, there are two core objects, React and ReactDOM. Here you can create an h1 element through the React object. First introduce this object.

import React from "react";
Copy after login

Then call the createElement method to create the element. The first parameter of this method is the node type we need to create. Here I need to create an h1 element, and the parameter is h1. The second parameter is the attribute setting owned by this element. If there is no attribute, you can directly give the null value. , the third parameter is the child element of the element. Here we need to display Hello World under the h1 element, then we can pass this string as its child element. The return value of this method is a react element. We can print this object on the console.

const h1Ele = React.createElement("h1", null, "Hello World");
console.log(h1Ele)
Copy after login

We can see from the console that it is an ordinary javascript object. This object has some attributes to describe the real elements. For example: the type attribute here is used to describe the type of this element, which means that this object maps to an h1 element. Similarly, props.children here refers to the child elements under this element, which is Hello World string.

Introduction to the method of creating React Element (detailed process)

Now that we have completed the creation of the react element, the next step is to turn this element into a real DOM node and add it to our page go. At this time, you need to use ReactDOM objects to complete the rendering of real nodes. First introduce this object.

import ReactDOM from "react-dom"
Copy after login

On the ReactDOM object, there is a render method, which is specially used to render react elements into real DOM. This method receives 2 parameters. The first parameter is the react element we need to render. Here we directly use the h1 element we just created; the second parameter is where on the page these elements need to be displayed. Open the index.html page, and we can find that there is a blank p element in this page. This element is called a container and is specially used to store these elements generated by react. So here, we can use this element as the second parameter of the render method. After saving, viewing the page, we can see a Hello World displayed on the page.

ReactDOM.render(h1Ele, document.querySelector("#root"))
Copy after login

Next step, how do we add style to this node? Returning to the method that just created the node, we can actually set the style of this node in the second parameter of this method. For example, if I now need to make the font color of h1 red, then specify it directly style color: red is fine.

const h1Ele = React.createElement("h1", {
  style: {
    color: "red"
  }
}, "Hello World");
Copy after login

In addition to using the style attribute, we can still modify it by introducing an external style sheet. Here I create a new css file, add a class selector, set the font size to 50px, and then in index.js, we use import to introduce this css file:

// theme.css
.msg {
  font-size: 50px;
}

// index.js
import "./theme.css"
Copy after login

然后在创建这个元素的时候,指定这个元素的 className 为 msg 就可以了,这时我们可以看到这个样式表就应用到当前这个元素了。

const h1Ele = React.createElement("h1", {
  style: {
    color: "red"
  },
  className: "msg"
}, "Hello World");
Copy after login

多个子元素的传递方式

接下来,我想再渲染一个列表应该如何操作呢?比方说,在这个列表中要显示 3 个选项,分别是 HTML,CSS 和 JAVASCRIPT。那我们第一步应该要创建这些节点。

首先引入 React 对象,使用 createElement 方法创建第一个 li 元素,第一个显示 HTML,然后再创建两个相同的元素,分别显示 CSS 和 JAVASCRIPT。

const li_01 = React.createElement("li", null, "HTML")
const li_02 = React.createElement("li", null, "CSS")
const li_03 = React.createElement("li", null, "JAVASCRIPT")
Copy after login

子元素创建完成之后,我们再来创建一个 ul 元素,因为这个ul元素有多个子元素,因此,这里有两种方式可以来传递子元素,第一种,我们可以把每一个子元素都当成参数传递给 createElement 方法

const ulEle = React.createElement("ul", null, li_01, li_02, li_03)
Copy after login

完成之后,将 ulEle 元素通过 render 方法渲染出来。查看页面,可以看到列表已经成功显示。

第二种方法,我们还可以将这些子元素变成一个数组交给 createElement 方法完成渲染,查看页面,我们可以看到列表依然正常显示,但是控制台给咱们抛出了一个警告:

Introduction to the method of creating React Element (detailed process)

这个警告的原因是,如果我们通过数组迭代的方式来创建子元素的话,我们需要给每一个子元素添加一个key的属性,而且这个属性的值,在同级元素中必须是唯一且不变的。那这里,我们给每一个li元素都增加一个key,值得话,让他们保证唯一就可以了。再查看页面,这时警告就消失了。

const li_01 = React.createElement("li", { key: 0 }, "HTML")
const li_02 = React.createElement("li", { key: 1 }, "CSS")
const li_03 = React.createElement("li", { key: 2 }, "JAVASCRIPT")
Copy after login

当然,这里我们还可以定义一个数组,然后通过迭代数组来产生这些li元素,这样可以简化一下我们的代码:

const arr = ["HTML", "CSS", "JAVASCRIPT"]
const liEles = arr.map((item, index) => {
  return React.createElement("li", {
    key: index
  }, item)
})
const ulEle = React.createElement("ul", null, liEles)
Copy after login

The above is the detailed content of Introduction to the method of creating React Element (detailed process). 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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks 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.

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles