1. HTML templates
JSX is react's grammatical sugar and will eventually be compiled into JS syntax. Therefore, a third-party library browser is required to convert JSX to JS.
Since the react 0.14 release, the react and react-dom are split, so you need to introduce react and react-dom separately
This is a demo on the official website.
1 <! DOCTYPE html>
2 <html>
3 <head>
4 <script src = "../ build / react.js"> </ script>
5 <script src = "../ build / react-dom.js"> </ script>
6 <script src = "../ build / browser.min.js"> </ script>
7 </ head>
8 <body>
9 <div id = "example"> </ div>
10 <script type = "text / babel">
11 ReactDOM.render (
12 <h1 color> Hello, world! </ H1>,
13 document.getElementById (‘example’)
14);
15 </ script>
16 </ body>
17 </ html>
But after compilation is like this:
React.render (React.createElement ("h1", {color: "red"}, "Hello, world!"), Document.getElementById (‘example‘));
The html code in the render () method is converted to React.createElement. Therefore, it is possible to use React.createElement to create templates, but it is not recommended.
React.createEleemt (type, [props], [... children]):
Type: the type argument can be either a tag name string (such as "div"), or a React Compoment ()
Jsx syntax rules: the first parameter of the render method, if the first letter is lowercase, it is HTML code, if it is uppercase, it is React component;
Jsx will take the initiative to check whether the label is closed, if not closed, directly report an error.
2.ReactDOM.render () + js
Just use braces to use js syntax.
1 var names = [‘Alice’, ‘Emily’, ‘Kate’];
2
3 ReactDOM.render (
4 <div>
5 {
6 names.map (function (name) {
7 return <div> Hello, {name}! </ Div>
8 })
9 }
10 </ div>,
11 document.getElementById (‘example’)
12);
Becomes:
1 var names = [‘Alice’, ‘Emily’, ‘Kate’];
2 React.render (
3 React.createElement ("div", null, names.map (function (name) {
4 return React.createElement ("div", null, "Hello,", name, "!")
5})),
6 document.getElementById (‘example’)
7);
There are still three parameters, the second arg is null, and the third parameter is the js code. So js code can only put one line of expression, there can't be; appear.
For example, it is wrong to write:
1 React.render (
2 <div>
3 {
4 var a = 1;
5 names.map (function (name) {
6 return <div> Hello, {name}! </ Div>
7})
8 }
9 </ div>,
10 document.getElementById (‘example’)
11);
3.render array
Arr is an array, jsx will add all the members of arr to the template. Just use {} to enclose arr to indicate js code.
var arr = [
<h1> Hello world! </ h1>,
<h2> React is awesome </ h2>,
];
ReactDOM.render (
<div> {arr} </ div>,
document.getElementById (‘example’)
);
The result after compilation:
1 React.render (
2 React.createElement ("div", null, [<h1> Hello world! </ H1>, <h2> React is awesome </ h2>,]),
3 document.getElementById (‘example’)
4);
react study notes-01