React element rendering


Release date:2024-03-09 Update date:2024-03-15 Editor:admin View counts:55

Label:

React element rendering

Elements are the smallest units that make up a React application and are used to describe what is output on the screen.

const element = <h1>Hello, world!</h1>;

With the browser’s DOM elements are different. Elements in React are actually ordinary objects. React DOM ensures that browsers DOM the datacontent of the React the elements are consistent.

Render elements into DOM

First, we add an id= “example” to a HTML page <div> :

<div id="example"></div>

Here div everything in will be managed by React DOM, so we call it the “root” DOM node.

We use React generally, only one root node is defined when developing an application. But if you are introducing it into an existing project React if so, you may need to define separately in different parts React root node.

To set the React elements are rendered to the root DOM node, we pass them all to the ReactDOM.render() to render it to the page:

Example

constelement=
<h1>Hello,world!</h1>;ReactDOM.render(element,document.getElementById('example'));

Update element rendering

React elements are immutable. After an element is created, you cannot change its contents or attributes.

Currently, the only way to update the interface is to create a new element and pass it in ReactDOM.render() methods:

Take a look at an example of this timer:

Example

functiontick(){constelement=(<div> <h1>Hello,world!</h1>
<h2>Now it's {newDate().toLocaleTimeString()}.</h2>
</div>);ReactDOM.render(element,document.getElementById('example'));}setInterval(tick,1000);

The above examples are passed through setInterval() method, call once per second ReactDOM.render() .

We can encapsulate the part we are going to show, and the following example is represented by a function:

Example

functionClock(props){return(<div> <h1>Hello,world!</h1>
<h2>Now it's {props.date.toLocaleTimeString()}.</h2>
</div>);}functiontick(){ReactDOM.render(<Clockdate={newDate()}/>,document.getElementById('example'));}setInterval(tick,1000);

In addition to functions, we can also create a React.Component the ES6 class, which encapsulates the elements to be displayed, should be noted in the render() method, you need to use the this.props replace props :

Example

classClockextendsReact.Component{render(){return(<div>
<h1>Hello,world!</h1>
<h2>Now it's {this.props.date.toLocaleTimeString()}.</h2>
</div>);}}functiontick(){ReactDOM.render(<Clockdate={newDate()}/>,document.getElementById('example'));}setInterval(tick,1000);

React will only update the necessary parts

It is worth noting that React DOM first compares the contents of the elements in order, while only the changed parts are updated during rendering.

Powered by TorCMS (https://github.com/bukun/TorCMS).