React.js Basic Primer Four--Essentials summary

Source: Internet
Author: User
Tags script tag

The JSX syntax, like the syntax for writing XML directly in JavaScript code, is essentially a syntactic sugar, and each XML tag is converted into pure JavaScript code by the JSX conversion tool, React the official recommendation to use JSX, Of course, it's also possible to write directly with pure JavaScript code, but using JSX, the structure of the component and the relationship between the components look clearer.


1. HTML tags and React components

In JS to write HTML tags, perhaps the small partners are stunned, then react how to distinguish between HTML tags, react component tags?


HTML Tags:


var mydivelement =; React.render (Mydivelement, document.body);


React Component Tags:


    1. var div= react.createclass ({/*...*/});

    2. var myelement = << span= "" >Div someproperty={true}/>;

    3. React.render (MyElement, document.body);

Breaking:

1. Note the beginning of capital *

2. Do not arbitrarily document.body, it is overwrite not append. (Timely code to find back)

3. Attribute Someproperty={true}


is not very simple, at a glance found, congruatulations smart you already understand!



2. Jsx and the original eco-JavaScript

Use Jsxreact.render (Content,document.getelementbyid (' example '));//Do not use Jsxreact.render (' div ' , Null,react.createelement (' div ', null,react.createelement (' div ', null, ' content ')), document.getElementById (' Example '));

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

In the API:

React.createelement

Reactelement createelement (string/reactclass type, [object props], [children ...]) #注意此处的省略号

The first argument can be a string representing an element within an HTML standard, or an object of type Reactclass, representing the custom component 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.



Conversion of JSX

React JSX The tags, attributes, and child elements of an element are passed as arguments to the React.createElement method:

Jsxvar Nav;var app =;//native Jsvar Nav;var app = React.createelement (Nav, {color: "blue"});
JSX Converters

This tool converts files that use JSX syntax into pure JavaScript files that can be run directly inside the browser. It will also monitor the directory for you, and then automatically convert the changed files


There are several ways to convert code with JSX syntax into pure JavaScript code:

1. For inline and HTML code or an external file that is not converted, add type= "TEXT/JSX" to the script tag and introduce the Jsxtransformer.js file.





2. However, this approach is not recommended for use in a production environment, and the recommended approach is to convert the code well before the code goes live, and you can use NPM to install React-tools globally:

#npm Install React-tools-g


and use the command line tool to convert (for specific usage can be consulted jsx -h 或者 jsx --help ) JSX through watch real-time monitoring, specific use to see help it. Here are just a few examples:

# JSX--watch src/build/

(#表示linux中的用户权限, Windows users can ignore it)


Great love boundless react. Render

The React.render method can render the HTML structure or render the React component.

(Repeat here for demo only)

    1. Renders the HTML tag, declaring the variable with the first letter small Write

var mydivelement =; React.render (Mydivelement, document.body);

2. Render the react component, declaring the variable with the first letter written

var mycomponent = React.createclass ({/*...*/}); var myelement =; React.render (MyElement, document.body);


However, it is important to note that the class for JSX syntax is ultimately converted to pure JavaScript, as well as the attributes (not quite sure how many, as the lookup API is subsequently added), so as in JavaScript className Dom htmlFor .

Use Jsxreact.render (Content,document.getelementbyid (' example '));//Do not use Jsxreact.render (React.createelement (' Label ', {className: ' xxx ', htmlfor: ' Input '}, ' content '), document.getElementById (' example '));

I believe you can see the difference at a glance.


Hateful but lovely:

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 attributes data- .


On the same code:

var htmloptions = React.createclass ({render:function () {return (attribute extension);}}); var ys =; React.render (Ys, document.getElementById (' htmls '));

After rendering, see if your tag always has the properties of ZZ, congratulations ...

Did you not? Haha, that's right, try to replace ZZ with Data-zz.


look tall on the usage (cover)

Some people say that, after using these formulations, will not write the original JS code, yes, lazy (and) do (harmonic) will be celestial.

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 = ();

In-stream: Here again (this is our hobby, in order to improve quality)

React Component Labels

This notation means self-closing tags (


Also note: All caps are capitalized, and the parent component tags are added. Why is it? Follow


This allows you to simply use the reactclass of the subassembly as the property of its parent component:

var myformcomponent = React.createclass ({...}); Myformcomponent.row = React.createclass ({...}); Myformcomponent.label = React.createclass ({...}); Myformcomponent.input = React.createclass ({...});


Render again using the form of subcomponents and parent components.


However, this is also possible:

var App = (react.createelement (Form, NULL, react.createelement (Form.row, NULL, react.createelement (Form.label, n ull), react.createelement (form.input, null)));

This feature requires version 0.11 and above

JavaScript expressions

writing JavaScript expressions in JSX syntax requires only   {}  , such as the following example using the three-mesh operator:

JSX is the syntax for HTML and JavaScript mash-up when encountering   <  ,jsx as HTML parsing, encountering   {   as JavaScript parsing.

Input (JSX): var content = <container>{window.isloggedin? <nav/>: <login/>}</container>;//O Utput (JS): var content = react.createelement (Container,null,window.isloggedin? React.createelement (NAV): React.createelement (Login));

Property expressions
React.render (<div classname={2 > 1? ' Class-a ': ' Class-b '}>content</div>,document.body);
Sub-expression
var Nav = React.createclass ({render:function () {return <div>nav</div>}}); React.render (<div> {2 > 1 <Nav/>: <div>div</div>}</div>,document.body);

Lie down, so easy!, aren't you?

Believe you would have thought of writing more bunkers like this.

This jsx:<div id={if (condition) {' msg '}}>hello world!</div>//are transformed to this JS:React.createElem ENT ("div", {id:if (condition) {' msg '}}, "Hello world!");


How tall. Unfortunately, it's wrong.

This reminds me of the syntax of HTML and PHP confusion in PHP.

<div><?php if (1>0) {echo ' Bunker ';}?></div>

or Pyhon.

[X+n for X in range (0,100) for n in range (0,10) if x%3==0 if n%5==0]

Don't understand, super bunker Ah! CAO, is ugly, not looking hard.



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>




The following are purely assignment-pasted: But proven, very good

Propagation properties (Spread Attributes)

It's easy to write if you know the properties of the component in advance. For example, the component component has two dynamic properties Foo and bar:

var component = <component foo={x} bar={y}/>;

In fact, some properties may be added later, we have no way to determine from the beginning, we may write the following bad code:

var component = <component/>;component.props.foo = x; Badcomponent.props.bar = y; Also bad

This is wrong, because we manually add the property react follow-up no way to check the property type error, that is, when we manually add a property of a type error, the console is not able to see the error message.

In the react setting, the props is immutable after the props is initialized. Changing props can cause unimaginable consequences.

Extended Properties

To solve this problem, react introduced a property extension

var props = {};p rops.foo = X;props.bar = Y;var component = <component {... props}/>;//or var props = {foo:x, bar:y };var component = <component {... props}/>;

This is equivalent to:

var component = <component foo={x} bar={y}/>

When we need to expand our properties, we define a Property object and {... props} Introduced in the JSX, you can use the...operator that represents the key value pair of an objectReactElementOfpropsAttribute Merge, this...The implementation of the operator is similar to the ES6 array in the...The attributes of the operator. , react will help us copy to the component's props property. The important thing is that this process is manipulated by react, not by manually adding the assigned Value property.

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 '
JSX Trap Style Property

When writing inline styles in react, this is not the way to write quotes

React.render (<div style={{color: ' Red '}}>xxxxx</div>,document.body);
HTML escape

For example, we have some content is the user input rich text, from backstage to the data to show on the page, want to show the corresponding style.

var content= ' <strong>content</strong> '; React.render (<div>{content}</div>,document.body);

The results page outputs the content directly:

<strong>content</strong>

React is HTML-escaped by default, avoids XSS attacks, and, if not escaped, can be written like this:

var content= ' <strong>content</strong> '; React.render (<div dangerouslysetinnerhtml={{__html:content}}></div>,document.body);




Finally recommend a blog post: (no See, everyone can refer to reading)

http://blog.csdn.net/lihongxun945/article/details/45826851

http://blog.csdn.net/lihongxun945/article/category/5195241

Nanyi's React.js Primer



This article comes from the link: http://sowm.cn/css88/article/q6fiAf.html

This article from the "90 Design Studio" blog, reproduced please contact the author!

React.js Basic Primer Four--Essentials summary

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.