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:
<div class='app' id='appRoot'> <h1 class='title'>欢迎进入React的世界</h1> <p> React.js 是一个帮助你构建页面 UI 的库 </p> </div>
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 的库'] } ] }
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 ( <p className='app' id='appRoot'> <h1 className='title'>欢迎进入React的世界</h1> <p> React.js 是一个构建页面 UI 的库 </p> </p> ) } } ReactDOM.render( <App />, document.getElementById('root') )
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') )
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] )
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