React JSX Syntax Description

Source: Internet
Author: User

Original: http://my.oschina.net/leogao0816/blog/379487

What is JSX?

When you write components with react, you usually use the JSX syntax, which looks like the XML tag is written directly in JavaScript code, which is essentially a syntactic sugar . Each XML tag is converted into pure JavaScript code by the JSX conversion tool, but it is also possible to write directly with pure JavaScript code, but with JSX, the structure of the component and the relationship between the components look clearer.

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

An XML tag, such as <MyComponent someProperty={true} /> what will be converted to by the JSX conversion tool?

Like what:

var Nav = React.createClass({/*...*/});var app = <Nav color="blue"><Profile>click</Profile></Nav>;

will be converted to:

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

So in other words, we write an XML tag that essentially calls React.createElement this method and returns an ReactElement object.

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

The first parameter of this method can be a string representing an element within an HTML standard, or an object of a ReactClass type that represents a custom component that we previously encapsulated. The second argument is an object, or a dictionary, that holds all of the intrinsic properties of the element (that is, the value that basically does not change after it is passed in). Starting with the third argument, the subsequent arguments are considered to be child elements of the element.

JSX Converters

To convert code with JSX syntax into pure JavaScript code, there are several ways to add and introduce files to inline and HTML code, or to external files that are not converted, script type="text/jsx" JSXTransformer.js But this is not recommended for use in a production environment , the recommended approach is to convert the code well before the code goes live, and you can use a npm global installation react-tools :

install -g react-tools

and use the command line tool to convert it (for specific usage, refer to jsx -h ):

jsx src/ build/

If you use an automation tool, for example gulp , you can use the appropriate plugin gulp-react .

Using HTML tags

To create an element that exists in an HTML standard, just as you would write HTML code:

var myDivElement = <div className="foo" />;React.render(myDivElement, document.body);

However, it is important to note that with class for These two attributes, the JSX syntax is ultimately converted to pure JavaScript, so it is used in the same way as in the JavaScript Dom className htmlFor .

Also, when creating elements within an HTML standard, the JSX Converter discards non-standard attributes, and if you must add custom attributes, you need to prefix these custom properties data- .

<div data-custom-attribute="foo" />
namespace-type Components

For example, when developing a component, a component has multiple subcomponents that you want to be a property of its parent component, so you can use it like this:

var Form = MyFormComponent;var App = (  <Form> <Form.Row> <Form.Label /> <Form.Input /> </Form.Row> </Form>);

This allows you to simply use the subcomponents ReactClass as the properties of their parent components:

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

The creation of child elements can be delivered directly 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 feature requires version 0.11 and above

JavaScript expressions

Writing JavaScript expressions in the JSX syntax only needs to be used {} , such as the following example using the three-mesh operator:

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

However, it is important to note that JSX syntax is only a syntactic sugar, it is behind the invocation ReactElement of the construction method React.createElement , so similar to the wording is not possible:

// This JSX:<div id={if (condition) { ‘msg‘ }}>Hello World!</div>// Is transformed to this JS:React.createElement("div", {id: if (condition) { ‘msg‘ }}, "Hello World!");

You can see the obvious syntax errors from the converted JavaScript code, so don't use the trinocular operator, or write this:

if (condition) <div id=‘msg‘>Hello World!</div>else <div>Hello World!</div>
Propagation properties (Spread Attributes)

In Jsx, you can use ... an operator that represents a property that combines the key-value pairs of an object with an implementation that resembles the attributes of an ReactElement props ... operator in an ES6 array ... .

var props = { foo: x, bar: y };var component = <Component { ...props } />;

This is equivalent to:

<Component foo={x} bar={y} />

It can also be mixed with normal XML attributes, requiring the same name attribute, which overrides the former:

var props = { foo: ‘default‘ };var component = <Component {...props} foo={‘override‘} />;console.log(component.props.foo); // ‘override‘
Resources (links may not be opened directly)
    • JSX in Depth
    • JSX Spread Attributes
    • If-else in JSX
    • JSX Gotchas

React JSX Syntax Description

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.