Getting started with JSX syntax in JavaScript React framework

Source: Internet
Author: User
This article mainly introduces the JSX grammar learning tutorials in the React framework of JavaScript. React is a highly popular js framework developed and open-source by Facebook. For more information, see What is JSX?

When using React to write components, JSX syntax is usually used. It looks like the XML tag is directly written in Javascript code. In fact, this is just a syntactic sugar, every XML tag will be converted into pure Javascript code by JSX Conversion Tool. Of course, you can directly use pure Javascript code to write it, just using JSX, the relationship between component structure and component looks clearer.

var MyComponent = React.createClass({/*...*/});var myElement = 
 ;React.render(myElement, document.body);

An XML tag, such What will be converted to by the JSX Conversion Tool?

For example:

var Nav = React.createClass({/*...*/});var app = 
 
  
   click
  
 ;

Will be converted:

var Nav = React.createClass({/*...*/});var app = React.createElement( Nav, {color:"blue"}, React.createElement(Profile, null, "click"));

In other words, if we write an XML tag, we call the React. createElement method and return a ReactElement object.

ReactElement createElement( string/ReactClass type, [object props], [children ...])

The first parameter of this method can be a string, indicating an element in the HTML standard, or a ReactClass object, indicating the encapsulated custom component. The second parameter is an object, or a dictionary. It stores all the inherent attributes of the element (that is, the value that will not be changed after being passed in ). Starting from the third parameter, all subsequent parameters are considered as child elements of the element.

JSX Converter

There are multiple ways to convert code with JSX syntax into pure Javascript code. For inline and HTML code or external files that have not been converted, add type = "text/jsx" to the script tag and introduce JSXTransformer. js files, but this method is not recommended in the production environment. The recommended method is to convert the code before the code goes online. You can use npm to install react-tools globally:

npm install -g react-tools

And use the command line tool to convert the data (For details, refer to jsx-h ):

jsx src/ build/

If you use automation tools such as gulp, you can use the corresponding plug-in gulp-react.

Use JS in HTML templates

It is very convenient to use JS in HTML templates. You only need to enclose JS Code in braces.

var names = ['Alice', 'Emily', 'Kate'];  React.render( 

{ names.map(function (name) { return

Hello, {name}!

}) }

, document.getElementById('example') );

After compilation, it becomes like this:

var names = ['Alice', 'Emily', 'Kate']; React.render(  React.createElement("p", null, names.map(function (name) {  return React.createElement("p", null, "Hello, ", name, "!")  }) ),  document.getElementById('example') ); 

Note that braces are actually a variable output expression, and JSX directly uses the content in braces as React. the third parameter of createElement is passed in directly (without any modification), so only one expression can be put in it, and any statement that cannot be directly used as the third parameter is wrong, the following error occurs:

React.render( 

{ var a = 1; names.map(function (name) { return

Hello, {name}!

}) }

, document.getElementById('example') );

Obviously, the content in curly braces is directly placed on the third parameter. The syntax is incorrect.

This is also wrong:

React.render( 

{ var a = 1; }

, document.getElementById('example') );

Because React. createElement ("p", null, var a = 1;) is a syntax error.
You can also understand why the js expression in braces cannot end with a semicolon.

Note that JS variables output in attributes cannot be enclosed by quotation marks, otherwise they will be treated as strings without being parsed.
It should be like this:

Link

Use HTML tags

To create an HTML standard element, just like writing HTML code:

var myDivElement = 

;React.render(myDivElement, document.body);

However, it should be noted that the class and for attributes are converted to pure Javascript in the end. Therefore, like in Javascript DOM, use className and htmlFor.

Another point is that when creating HTML standard elements, the JSX converter will discard those non-standard attributes. If you must add custom attributes, you must add a data-Prefix before these custom attributes.

Namespace component

For example, when developing components, a component has multiple sub-components. You want these sub-components to be attributes of its parent component, you can use them as follows:

var Form = MyFormComponent;var App = ( );

In this way, you only need to take the ReactClass of the child component as the attribute of its parent component:

var MyFormComponent = React.createClass({ ... });MyFormComponent.Row = React.createClass({ ... });MyFormComponent.Label = React.createClass({ ... });MyFormComponent.Input = React.createClass({ ... });

The sub-elements can be directly handed over to the JSX converter:

var App = ( React.createElement(Form, null,  React.createElement(Form.Row, null,   React.createElement(Form.Label, null),   React.createElement(Form.Input, null)  ) ));

This function requires version 0.11 and later.

Javascript expressions

In JSX syntax, you only need to use {} To write Javascript expressions. For example, the following example uses the Three-object OPERATOR:

// Input (JSX):var content = 
 
  {window.isLoggedIn ? 
   : 
  }
 ;// Output (JS):var content = React.createElement( Container, null, window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login));

However, it should be noted that the JSX syntax is just a syntactic sugar. Behind it is the call of ReactElement's constructor React. createElement, so it is not possible to write something like this:

// This JSX:

Hello World!

// Is transformed to this JS:React.createElement("p", {id: if (condition) { 'msg' }}, "Hello World!");

You can see obvious syntax errors in the converted Javascript code, so you do not need to use the three-object operator, or you can write it like this:

if (condition) 

Hello World!

else

Hello World!

Propagation Attributes (Spread Attributes)

In JSX, you can use... operator that combines the key-value pairs of an object with the props attribute of ReactElement... the implementation of operators is similar to that in ES6 Array... operator features.

var props = { foo: x, bar: y };var component = 
 ;

This is equivalent:

var component = 
 

It can also be used in combination with common XML attributes. attributes with the same name are required, and the latter will overwrite the former:

var props = { foo: 'default' };var component = 
 ;console.log(component.props.foo); // 'override'
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.