React JSX
React uses JSX instead of regular JavaScript.
JSX is a JavaScript syntax extension that looks a lot like XML.
We don’t necessarily need to use JSX, but it has the following advantages:
JSX executes faster because it is optimized after being compiled into JavaScript code.
It is type-safe and errors can be found during the compilation process.
Writing templates using JSX is simpler and faster.
##Using JSX JSX looks similar to HTML, we can look at the example:
ReactDOM.render(We can nest it in the above code Multiple HTML tags need to be wrapped with a div element. The p element in the example has a custom attributeHello, world!
, document.getElementById('example') );
data-myattributeadded. To add a custom attribute, you need to use thedata-prefix.
Independent file Your React JSX code can be placed in an independent file. For example, we create ahelloworld_react.jsfile with the following code:
ReactDOM.render(Then Introduce the JS file into the HTML file:Hello, world!
, document.getElementById('example') );
JavaScript Expressions We can use JavaScript expressions in JSX. Expressions are written in curly braces
{}. The examples are as follows:
You cannot use theif elsestatement in JSX. You can use theconditional (ternary operation)expression instead. In the following example, if the variableiis equal to1, the browser will outputtrue. If the value of i is modified,false.# will be output.
##Instance StyleReact recommends using inline styles. We can use the
camelCasesyntax to set inline styles. React will automatically addpxafter specifying the element number. The following example demonstrates adding themyStyleinline style to theh1element:
ExampleComments
Comments need to be written in curly brackets , the example is as follows:
Array
JSX allows inserting arrays in templates, and the array will automatically expand all members:
##HTML tag vs. React component React can render HTML tags (strings) or React components (classes). To render HTML tags, just use lowercase tag names in JSX.
var myDivElement = ; ReactDOM.render(myDivElement, document.getElementById('example'));To render a React component, just create a local variable starting with a capital letter.
var MyComponent = React.createClass({/*...*/}); var myElement =React's JSX uses uppercase and lowercase conventions to distinguish local component classes and HTML tags.; ReactDOM.render(myElement, document.getElementById('example'));
Note: Since JSX is JavaScript, some identifiers likeclass
and
forare not recommended as XML Property name. Instead, React DOM uses
classNameand
htmlForfor corresponding attributes.