React's JSX syntax and components

Source: Internet
Author: User

Recently a colleague was in a hurry to take paternity leave without any handover, and then I came to maintain it. To tell the truth, I started out with a face that was crazy. Because the most used in the mv* project or Vue;react heard also know, but after all, not familiar ...

But no matter how this is the work, colleagues also congratulate colleagues as a father, playing psychology for him feel happy!

When the code is down and starts to look at it, the syntax basically uses CMD,ES6 and the Jsx,react component described in this article. Cmd,es6 This is not difficult after all, usually also used. But the Jsx,react component was a bit crazy at first,

But read a few more times and Baidu Google will understand.

(It seems a bit more nonsense, OK, start to focus ....) )

The first is JSX:

I started to look at the time, gee, how to write DOM do not need quotation marks? Later I knew that react invented JSX to use HTML syntax to create a virtual DOM. This is also one of the core of react. A virtual DOM element that can be created in memory. React uses virtual DOM to reduce the operation of the actual DOM to improve performance. Similar to the real native DOM, virtual Dom can also be created with JavaScript (react.createelement)

render () {   return react.createelement (' div ',null, ' content text ')  }

JSX itself is similar to XML syntax, and can define attributes and child elements. The only special thing is that you can use curly braces, the syntax in curly braces is a pure JavaScript expression, the return value is given to the component's corresponding property, so any JavaScript variable or function call can be used. Also use JavaScript expressions in curly braces to return elements that need to be represented.

Events in the JSX

JSX uses the hump notation to describe the event name, which is still the standard JavaScript expression in curly braces, returning an event handler function. In JSX you don't need to be concerned about the timing to remove event bindings, because react automatically removes event bindings when the corresponding real DOM node is removed. And the mode of the event broker: Add a unique listener for each event on the root node document, and then find the real trigger element through the target of the event. In this way, all nodes from the triggering element to the top-level node, if there is a binding event, react will trigger the corresponding event handler. This is known as the React Simulation event system. Although the entire event system is managed by react, its APIs and usage methods are consistent with native events. This mechanism ensures cross-browser consistency: All browsers (IE8 and above) can use the standard-compliant API, including Stoppropagation (), Preventdefault (), and so on. For event bubbling (bubble) and capture mode are also fully supported

<button onclick={checkandsubmit.bind (this)}>submit</button>
Using Styles in JSX

The use of styles and real styles in JSX is similar, as defined by the Style property, but unlike the real DOM, the property value cannot be a string and must be an object, for example:

<style' #ff0000 ', fontSize: ' 14px '}}>Hello World. </ Div >

The curly braces in this jsx are double, a bit odd, but in fact the curly braces are just standard JavaScript object expressions, and the outer braces are the JSX syntax. So, style you can also assign a value to a variable, and then pass it in, the code will be easier to read:

var style = {  color: ' #ff0000 ',  <style={style}> HelloWorld. </ Div >;

Note: You can use all the styles in jsx, basically the conversion specification of the property name is to write it as a camel, such as "Background-color" into "BackgroundColor", "Font-size" to " FontSize ", which is consistent with the standard JavaScript operation DOM-style API.

React Custom Components

First look at a react official demo:

class HelloWorld extends react.component{  render () {    return  (      <p>          <input type= "text" placeholder= "Your name here"/>!        It is {this. props.date.toTimeString ()}  {/* Gets the data passed through This.props.data */  }      </p>);}  ; SetInterval (function() {  react.render (    New Date ()}/>,    document.getElementById (' example ')  500);
Concept and life cycle of components

React uses components to encapsulate interface modules, the entire interface is a large component, the development process is to continuously optimize and split interface components, the construction of the entire component tree process. You can think of components as similar to the concepts of widgets (or control) in other frameworks, but they are different. The interface in react is all components, and widgets are generally just separate modules embedded in the interface to complete a function. For example, the entire page is a large component, and then it is split into many smaller components. The component mechanism plus the JSX syntax allows you to construct the interface as a set of HTML tags that match the needs of your project, and the interface definition becomes very intuitive.

The component itself defines a set of props as the external interface, each time the props change can be the idea of refreshing the page as a whole to consider the interface display logic. When presenting a component, you only need to specify props as the attribute of the XML node. Components rarely need to be exposed externally, the only way to interact is props. This makes using the component as simple as using a function, given an input, and the component is given an interface output. When the given parameters are certain, then the output is also certain. While traditional controls often provide many ways for you to change the state and behavior of a control externally, development and debugging can become complex when the state of the control is arbitrarily controlled in different logic in different scenarios.

If the entire project is fully react, then there is only one component root node on the interface, and if you use react locally, then each part of the local use has a root node. At render, the root node is triggered by the React.render function:

React.render (  <app/>,  document.getElementById (' React-root '));

All child nodes are constructed by the parent node's Render method. Each component will have a Render method that returns an instance of the component, and eventually the entire interface gets a virtual DOM tree, which is then presented to the interface in the most efficient way by react.

In addition to props, components have a very important concept: state. The SetState method is defined in the component specification, which updates the state of the component each time it is called, triggering the Render method. It is important to note that the Render method is called asynchronously, which guarantees that multiple setstate methods of synchronization will only trigger one render at a time, which can improve performance. Unlike props, state is the internal status of a component, which, in addition to being initialized, may be determined by props and then completely maintained by the component itself. Throughout the component's lifecycle, react strongly does not recommend modifying its own props, because it destroys the consistency of the UI and model, and props can only be determined by the user.

For custom components, the only method that must be implemented is render (), in addition to some methods that are called during the component life cycle, as shown in:

The method in the diagram has almost already included all of react's APIs, and the custom component implements different logic at different stages of the component's lifecycle as needed. In addition to the required render methods, other commonly used methods include:

Componentdidmount: Called after the component first render, the DOM node corresponding to the component has been added to the browser. In this method you can implement some initialization logic.

Componentwillunmount: Called after the DOM node has been removed, you can do some cleanup work here.

Shouldcomponentupdate: This is a very performance-related method that is called before each render method. It provides an opportunity for you to decide whether or not to actually render the component.

shouldcomponentupdate (Nextprops, nextstate) {  returnthis. props.id;}

When this function returns FALSE, the component does not call the Render method to avoid the creation of virtual Dom and diff comparisons in memory, which can help improve performance. When True is returned, normal render logic is performed.

Components are the core of react, and although they are powerful, their APIs and concepts are so simple that you can create a component simply by implementing a Render method. This greatly reduces the react learning threshold.

Reference and original address: http://www.infoq.com/cn/articles/react-jsx-and-component/

React's JSX syntax and components

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.