Know JSX principles in one article (recommended)

藏色散人
Release: 2022-01-14 09:04:53
forward
1556 people have browsed it

To understand the principles of JSX, you need to first understand how to use JavaScript objects to express the structure of a DOM element.
Look at the DOM structure below:

欢迎进入React的世界

React.js 是一个帮助你构建页面 UI 的库

Copy after login

We can use JavaScript objects to represent all the information in the above HTML:

{ tag: 'p', attrs: { className: 'app', id: 'appRoot'}, children: [ { tag: 'h1', attrs: { className: 'title' }, children: ['欢迎进入React的世界'] }, { tag: 'p', attrs: null, children: ['React.js 是一个构建页面 UI 的库'] } ] }
Copy after login

But this is too long to write in JavaScript, and the structure It's not clear either, it's very convenient to use HTML.
So React.js expanded the syntax of JavaScript to allow writing syntax similar to HTML tag structures in JavaScript code, which is much more convenient. The compilation process will convert JSX structures similar to HTML into JavaScript objects. structure.

import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { render () { return ( 

欢迎进入React的世界

React.js 是一个构建页面 UI 的库

) } } ReactDOM.render( , document.getElementById('root') )
Copy after login

Convert to

import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { render () { return ( React.createElement( "p", { className: 'app', id: 'appRoot' }, React.createElement( "h1", { className: 'title' }, "欢迎进入React的世界" ), React.createElement( "p", null, "React.js 是一个构建页面 UI 的库" ) ) ) } } ReactDOM.render( React.createElement(App), document.getElementById('root') )
Copy after login

React.createElement will construct a JavaScript object to describe your HTML structure information, including tag names, attributes, sub-elements, etc. The syntax is

React.createElement( type, [props], [...children] )
Copy after login

The so-called JSX is actually a JavaScript object, so when using React and JSX, you must go through the compilation process

JSX — Use react to construct components, and babel compiles them—> JavaScript objects— ReactDOM .render()—> DOM element—> Insert page

Recommended learning: "JS Basic Tutorial"

The above is the detailed content of Know JSX principles in one article (recommended). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
jsx
source:segmentfault.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!