Introduction to React non-dom attributes
Non-dom attributes?
dangerouslySetInnerHTML,ref,key
Non-dom standard attributes, that is to say, there are no specified attributes in the dom standard. React introduces three non-dom attributes, as above.
dangerouslySetInnerHTML: Literally, dangerously setting internal html. The function of this attribute is to directly insert html code in jsx. Why do we use this attribute to insert html code? Instead of writing it directly when writing code? Because sometimes when we write code, we cannot confirm what code to insert, which means that this part of the html code is dynamically generated. In other words, it was not written by us, so why is this behavior dangerous? There is a word called cross-site attack. The reason why cross-site attack occurs is because of the function of directly writing code. Let's give an example, If there is a content to be displayed on the page, this content comes from the user's input. Assume that the user's input contains code, such as js code, html code. If we use it directly without testing, insert this dom into the page. Then when other people visit the page, the code written by this person will be executed. Since we cannot judge the user's intention, he may write very dangerous code, such as adding a connection to a Trojan, then Users who visit this page will be infected with viruses or download Trojans without knowing it. This is very dangerous, but sometimes we really need to dynamically write code, so react still provides this attribute, but it is clearly stated in the name. It tells you that this attribute is very dangerous, so try not to use it.
ref: The abbreviation of reference. The parent component refers to the child component. When we write components, we often use nesting. If the parent component has nested child components, it needs to be used when the parent component refers to the child component. ref, in actual use, ref actually maintains many references in the parent component, and each reference refers to a corresponding child component, so that we can operate the child component through these references in the parent component. Why can't we operate the parent component of the parent component? This is actually not a code problem, but a design problem. The purpose of using components in react is to modularize the code. Each component only needs to consider its own functions and logic, and does not need to care about who is using it, so the component does not need Referring to its own parent component, the interaction between the parent component and the component is achieved through the transfer of attributes, which we will talk about later. But such transfer is one-way, that is to say, attributes are always transferred from top to bottom, and the components below will not control the components above. This is to make the logic clearer,
key: improve rendering performance. One of the characteristics of react is its good performance. This is because it removes manual DOM operations and implements it completely automatically. However, automatic implementation means that it has a set of algorithms, which means that when the page changes, react needs to apply this set of algorithms. Algorithm to determine how to modify the page efficiently to reflect the corresponding changes. This algorithm is often called diff, which is the abbreviation of different, which means calculating the difference between two states.
react diff algorithm
Flowchart of react diff algorithm
First of all, we need to make it clear that what we are comparing now are two components. Everything in react is a component, so as long as we understand how the two components are compared, other structures can be used Break it down into components for comparison.
The leftmost side is the start. The first judgment after the start is whether the nodes are the same. The same means that div and div are the same, div and p are different, or our customized HelloMessage and HelloMessage are the same, HelloMessage It is not the same component as HelloWorld. If the nodes are the same, the subsequent comparison will be performed. If the nodes are different, react will directly discard the old node and generate a brand new node. Here react is based on an assumption. If the two nodes are different, Then their content is very different. If the nodes are different, we will directly end the comparison and generate a brand new node. If the nodes are the same, the next step to determine is whether these points are custom nodes or standard nodes of dom, that is, whether they are divs or HelloWorld. If It is said that it is not a custom node, but a standard node. Then the next step that react needs to do is to compare the attributes of the two nodes, such as class, id, etc. If the attributes are exactly the same, it means that the two nodes are the same, and the comparison ends. ; If the attributes are different, write down the different attributes and apply the changes. For example, if there is a new attribute, add a new attribute, and if there is one attribute missing, delete an attribute. Similar operations. That is to say, react will not delete the old node, but will only operate on it. If it is a custom node, react will re-render it. We will learn properties and states later. A component has many states. If it is the same custom component, then the new component may be just a state of the old component. Reac The new state will be passed into the old component, and then the rendering results of the component will be compared and changes will be made. In other words, react will still not regenerate the component, but will make changes to the old component. This is the diff algorithm. the entire process. So what is the use of key? The role of key is mainly reflected in the comparison of nodes. Suppose we have a list-like node, that is, there are multiple child nodes in the parent node. If there is no key and we make changes, React will compare stupidly from left to right. , for example, before the change, there was only node 1. After the change, we insert a node 2 and it becomes node 2 and node 1. Then the operation performed by react is to delete node 1, add node 2, and add node 1, that is to say , react cannot determine whether node 1 in the new state is the same as node 1 in the state, so it can only delete all the different ones, even if they may be the same, which will cause performance problems, then the purpose of introducing key is to Add a unique identifier to each node. In this way, by comparing the keys, react can know which nodes are the original nodes and which nodes are the newly added nodes. For the example we just mentioned, node 1 becomes node 2. 1. At this time, react only needs to do one operation, which is to insert node 2. Because the key of node 1 is the same, it means that they are the same node and there is no change.
Understanding this principle, what inspiration does it have for us to write react components?
The first point is that if two components are very similar, then try to write them as one component, because we have seen in the process that two different components will definitely be regenerated, even if their contents are very similar. The second revelation is that if you use a similar list to display elements, try to add keys to the elements. This can greatly improve efficiency and avoid unnecessary performance losses.
How to use non-dom attributes?
dangerously instance
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>hello world</title> </head> <body> <script type="text/javascript" src="http://cdn.bootcss.com/react/0.13.2/react.js"></script> <script type="text/javascript" src="http://cdn.bootcss.com/react/0.13.2/JSXTransformer.js"></script> <script type="text/jsx"> var style={ color:"red", border:"1px solid #f09", }; var rawHTML={ __html:"<h1 id="I-nbsp-am-nbsp-inner-nbsp-HTML">I am inner HTML</h1>" }; var HelloWorld=React.createClass({ render: function(){ return <p>Hello,world</p> } }); React.render(<div style={style} dangerouslySetInnerHTML={rawHTML}></div>,document.body); </script> </body> </html>
ref instance, please note that what you get through the reference is not the dom node itself, which means that we cannot perform operations between doms, such as setting text, this is not possible, we get is just a virtual dom node, which is the dom node displayed to us by react. If you want to get the real dom node, you need to call a method. We will talk about it later, but react does not encourage us to do this. Unless under special circumstances, we need to operate the dom node, in other cases react will help us operate it.
This example is not complete, we will continue to explain it later.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>hello world</title> </head> <body> <script type="text/javascript" src="http://cdn.bootcss.com/react/0.13.2/react.js"></script> <script type="text/javascript" src="http://cdn.bootcss.com/react/0.13.2/JSXTransformer.js"></script> <script type="text/jsx"> var style={ color:"red", border:"1px solid #f09", }; var rawHTML={ __html:"<h1 id="I-nbsp-am-nbsp-inner-nbsp-HTML">I am inner HTML</h1>" }; var HelloWorld=React.createClass({ render: function(){ this.refs.childp return <p ref="childp">Hello,world</p> } }); React.render(<div style={style} dangerouslySetInnerHTML={rawHTML}></div>,document.body); </script> </body> </html>
Key instance: Note that inside each component, the value of key must be different. Note that it is inside the component! There is no such restriction between the two components.
Remember two points: 1. Try to merge components with similar content into the same component. 2. List type elements must be added with a unique key. By doing these two points, you can avoid many performance problems.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>hello world</title> </head> <body> <script type="text/javascript" src="http://cdn.bootcss.com/react/0.13.2/react.js"></script> <script type="text/javascript" src="http://cdn.bootcss.com/react/0.13.2/JSXTransformer.js"></script> <script type="text/jsx"> var style={ color:"red", border:"1px solid #f09", }; var rawHTML={ __html:"<h1 id="I-nbsp-am-nbsp-inner-nbsp-HTML">I am inner HTML</h1>" }; var HelloWorld=React.createClass({ render: function(){ return <ul> <li key="1">1</li> <li key="2">2</li> <li key="3">3</li> </ul> } }); React.render(<div style={style} dangerouslySetInnerHTML={rawHTML}></div>,document.body); </script> </body> </html>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

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.

How to use React to develop a responsive backend management system. With the rapid development of the Internet, more and more companies and organizations need an efficient, flexible, and easy-to-manage backend management system to handle daily operations. As one of the most popular JavaScript libraries currently, React provides a concise, efficient and maintainable way to build user interfaces. This article will introduce how to use React to develop a responsive backend management system and give specific code examples. Create a React project first

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.

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 has closures such as event handling functions, useEffect and useCallback, higher-order components, etc. Detailed introduction: 1. Event handling function closure: In React, when we define an event handling function in a component, the function will form a closure and can access the status and properties within the component scope. In this way, the state and properties of the component can be used in the event processing function to implement interactive logic; 2. Closures in useEffect and useCallback, etc.

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.
