1. JSX syntax
In react, the syntax of jsx is used to display DOM elements. The react template of a basic jsx syntax is as follows:
<div>{this.props.title}</div>
The essence of this approach is: embed js expressions in html!!
How does the compiler compile jsx syntax? The rule is as follows: when it comes to parsing with "< beginning and" > "ending, it will be parsed according to HTML syntax; when it comes to parsing with" {"beginning and"} "ending, it will be parsed according to JavaScript expression.
JSX syntax is able to parse expressions (basic operation operation, binocular operator, array, etc.)
Examples of basic operations
Basic addition, subtraction, multiplication and division can be output.
var Hello = React.createClass({
render: function () {
return (
<h1>
hello world!
{ 1+1 }
</h1>
)
}
})
ReactDOM.render(<Hello />,document.getElementById('root'))
An example of three wood operation
The following isShow shows different pages as true or false.
var Hello = React.createClass({
getInitialState: function () {
return {
isShow: true
}
},
render: function () {
return (
<h1>
hello world!
{ this.state.isShow ? <span>123</span>:<span>456</span> }
</h1>
)
}
})
ReactDOM.render(<Hello />,document.getElementById('root'))
Analysis of array
JSX can parse arrays and return DOM elements.
var Hello = React.createClass({
render: function () {
return (
<h1>
hello world!
<ul>
{ [<li>123</li>,<li>123</li>,<li>123</li>] }
</ul>
</h1>
)
}
})
ReactDOM.render(<Hello />,document.getElementById('root'))
2. Conditional rendering
In react, conditional rendering is done by using the three wood operator.
var Hello = React.createClass({
getInitialState: function () {
return {
like: true
}
},
click: function () {
this.setState({
like: !this.state.like
})
},
render: function () {
return (
<h1>
hello world!
{ this.state.like?<span>I like you!</span>:<span>I dislike you!</span> }
<button onClick={this.click}>change</button>
</h1>
)
}
})
ReactDOM.render(<Hello />,document.getElementById('root'))
In this example, use the click function to change the state of the state, and display different things according to the change state.
3. List rendering
In react, jsx can parse the array, so in terms of implementation, we usually use the map method to realize DOM rendering.
var Hello = React.createClass({
getInitialState: function () {
return {
arr: ['mapbar_front','liwudi','I am Chinese,']
}
},
render: function () {
return (
<ul>
{ this.state.arr.map((item,index) => {
return (
<li key={index}>{item}</li>
)
})}
</ul>
)
}
})
ReactDOM.render(<Hello />,document.getElementById('root'))
The list rendering method is implemented by the map method, and the return value is an array, in which the item represents each item of the array, which will be rendered to the corresponding DOM.