Reactjs Introduction II

Source: Internet
Author: User
Tags diff

Reactjs Getting Started learning two

Reactjs Getting Started learning two

Read Catalogue

    • Background and fundamentals of react
    • Understanding React.render ()
    • What is JSX?
    • Why use JSX?
    • The syntax of JSX
    • How to use events in JSX
    • How to use styles in JSX
Back to Top

Background and fundamentals of react

In web development, we always need to change the data in real-time to the UI, then we need to manipulate the DOM, complex or frequent DOM operation is the cause of the performance bottleneck, react introduced the virtual DOM mechanism, the browser side using JavaScript to implement a set of DOM API, all DOM constructs based on react development are performed through the virtual DOM, and whenever the data changes, react reconstructs the entire DOM tree, and then react compares the entire DOM tree with the previous DOM tree to get the changed parts, Then the changes are made to the actual browser Dom update, and react is able to batch virtual DOM refreshes, two data changes within an event loop will be merged, for example, you can change the node content A to B in succession, and then change B to A,react will assume that the UI is not changed. Although it is necessary to construct a complete virtual DOM tree every time, the virtual DOM tree is memory data, the performance is very high, and the actual DOM operation is only a diff part, so you can improve performance. While guaranteeing performance, we will no longer need to focus on how changes in one data can be updated to one or more specific DOM elements, only to be concerned about how the entire interface is being render in any given data state.

React component:

The virtual DOM not only brings simple UI development logic, but also introduces the idea of component development, the so-called component, which is a packaged, self-contained UI part, react recommends a component-based way to rewrite the thinking UI composition, defining each functionally independent module of the UI as a component. The widgets are then transformed into large components in a nested way, resulting in a complete UI build. If the idea of MVC allows us to perform, data, and control the separation, then react in a modular way of thinking brings the separation between UI modules, such as the Site page I introduced in the previous article: for example:

The navigation bar, sidebar, and content area are nested to create a complete UI interface for each widget.

The react component should have the following characteristics:

    1. Composable: One component is easy to use with other components, or nested inside another component.
    2. Reusable: Each component has a separate function that can be used in multiple UI scenarios.
    3. Maintainable: Each small component contains only its own logic and is easier to understand and maintain.

The following is the first time we use react to refer to the following js,react.js and Jsxtransformer.js, the following HTML code is as follows:

<!doctype html>
Back to Top

Understanding React.render ()

React.render () is used to convert a template to an HTML language and insert the specified DOM node.

The following code:

React.render (    

The page generated HTML structure is as follows:

The page appears as follows:

Back to Top

What is JSX?

React's core mechanism is to implement a virtual DOM, using virtual DOM to reduce the operation of the actual DOM to improve performance, the component DOM structure is mapped to this virtual DOM, react in this virtual DOM implementation of a diff algorithm, when to update the component, Will find the DOM node to change through the diff, and then update the changes to the actual DOM node of the browser, so it is not really rendering the entire DOM tree, the virtual DOM is a pure JS data structure, so performance than the native Dom will improve a lot;

Virtual Dom can also be created using JavaScript, such as the following code:

var child1 = react.createelement (' Li ', null, ' first Text Content '), var child2 = react.createelement (' Li ', null, ' second Text Content '); var root = react.createelement (' ul ', {className: ' Test '},child1,child2); React.render (Root,document.getelementbyid ("demo"));

The rendered structure in the page becomes as follows:

The page appears as follows:

However, writing code is not readable, so react appears jsx, using the following way to create a virtual DOM;

var root = (        <ul classname= "Test" >            <li>first text content</li>            <li>second text content</li>        </ul>); React.render (Root,document.getelementbyid ("demo"));

The above 2 ways to achieve the same effect, many people may think that the introduction of a JSX source will affect the performance of the page, here we just for testing, if really in the development project, JSX in the product packaging phase will be compiled into pure JavaScript, JSX syntax does not have any performance impact.

Back to Top

Why use JSX?

The most basic function of front-end development is to show the data, so many frameworks have introduced the template engine, if we do not use the template, then we need to manually and followed by a very long HTML string, and this will be easy to error, the code is not very beautiful, and most importantly, the presentation of logic and business logic is not enough separation (using MVC thought); So react invented the jsx;

Back to Top

The syntax of JSX

JSX allows HTML to be mixed with JavaScript, the following code:

var names = [' Longen1 ', ' longen2 ', ' Longen3 ']; React.render (    <div classname= "AA" >        {            names.map (function (name) {                return <p>hello,{name }</p>            })        }        </div>,document.getelementbyid ("demo"));

JSX syntax rules are: encountered HTML tags (beginning with <), is to use HTML rules parsing, encountered code block (beginning with {), using JSX syntax rules parsing; The code above is generated as follows:

Understanding This.props

Props represents the properties of the component itself, which are some of the attributes or data that the parent node passes to the child layer node, as in the following code:

var hellomessage = React.createclass ({    render:function () {        return <div>hello {this.props.name}</ div>;    }}); React.render (

Understanding This.props.children

The properties of the This.props object correspond to the component's property one by one, but there is a column outside the This.props.children property. It represents all the child nodes of the component;

The following code:

var noteslist = React.createclass ({    render:function ()} {        return (            <ol>              {                This.props.children.map (function (child) {                  return <li>{child}</li>                })              }             </ol>        );     }}); React.render (     <NotesList>        <span>hello</span>        <span>world</span>    </noteslist>,    document.getElementById ("demo"));

The page appears as follows:

Understanding the React.createclass method

React allows the code to be encapsulated into components and then inserted like normal HTML, and the React.createclass method is used to generate a component class, as in the following code:

var NodeList = React.createclass ({    render:function () {        return 

As in code, NodeList is a component class that automatically generates a NodeList real column when the template is inserted into the <nodelist/>, and all components must have a render () method for the output component, as on <nodelist name= The "John"/> is added a property name, the properties on the component can be obtained using the This.props object, such as the Name property above can be read by this.props.name;

The page appears as follows:

Understanding This.state

This.state is a component-private, and we can change it by This.setstate (), then the component will re-render itself; The following code:

var Likebutton = React.createclass ({    getinitialstate:function () {        return {liked:false};    },    Handleclick:function (event) {        this.setstate ({liked:!this.state.liked});    },    render:function () {        var text = this.state.liked? ' Like ': ' haven\ ' t liked ';        Return (            <p onclick={this.handleclick}> you            {text}. Click to toggle.             (</p>        );    }}); React.render (    <likebutton/>,    document.getElementById (' demo '));

As the above code first uses the Getinitialstate () method to define the initial state (and only once), when the user clicks, call the Handleclick function, use this.setstate to dynamically change the value, after each change, will automatically call render () The rendering component.

What is the difference between This.props and this.state?

This.props refers to attributes that inherit from the parent element, and that properties cannot be changed.

This.state is the private of a component that can be changed dynamically;

Refs and Finddomnode ()

In order to interact with the browser, we sometimes need to get the real DOM node, we can get the real DOM in the component through React React.finddomnode (component);

The following code:

var mycomponent = React.createclass ({    handleclick:function () {        react.finddomnode (this.refs.myTextInput). Focus ();    },    render:function () {        return (            <div>                <input type= "text" ref= "Mytextinput"/ >                <input                      type= "button"                      value= "Focus the text input"                      Onclick={this.handleclick}                    /> (              </div>            );        }    });    React.render (        <mycomponent/>,        document.getElementById (' demo ')    );

The child node of the component MyComponent has a text input box, click the button, focus on the input box, this time we need to get to the mycomponent component of the real DOM node, in order to do this, the text input box must have a ref attribute, and then This.refs. [RefName] points to this virtual Dom child node, and finally gets the real DOM node through React.finddomnode.

Understanding React.createelement

Parameters: Type (string), Config (object), Children (child node)

The following code

var Commentbox = React.createclass ({    displayName: ' Commentbox ',    render:function () {        return (            React.createelement (' div ', {className: ' Commentbox '}, ' hello,world! I am a Commentbox ")        );    }); React.render (    react.createelement (commentbox,null), document.getElementById ("demo"));

The page appears as follows:

Understanding React.proptypes

When validating the use of components, the parameters provided are compliant, the properties of the component can accept arbitrary values, strings, objects, functions, such as the following code, to verify that the Title property in the component is a string, the following code:

var MyTitle = React.createclass ({  proptypes: {    title:React.PropTypes.string.isRequired  },  render: function () {     return  This.props.title = = 1234? <p> is a string </p>: null   }}); var data = "123"; React.render (  <mytitle title= "1234"/>,document.getelementbyid ("demo"));

As you can see, the print out of the page is a string;

Understanding React.isvalidelement

Parameter Object

Determines whether the parameter is a valid reactelement, and returns a Boolean value, as shown in the following code test

var Longen = React.createclass ({    render:function () {        return <p>123</p>     }}); var test = < Longen/>,test2 = ' <Longen/> '; Console.log (react.isvalidelement (test));  Trueconsole.log (React.isvalidelement (test2));  False
Back to Top

How to use events in JSX

We previously wrote the following events:

<button onclick= "Checkandsubmit (this.form)" >Submit</button>

There's no problem writing the code for a simple HTML page, but for a complex page, we can use JavaScript to bind the event: we can refer to jquery;

$ (' #id '). On (' Click ', This.checkAndSubmit.bind (this));

But in JSX we can bind events as follows:

<input type= "text" Value={value} Onchange={this.handlechange}/>

In JSX we don't need to worry about when to remove the event bindings, because react will automatically dismiss the event bindings when the corresponding real DOM node is removed;

React does not really bind events to each element, but instead uses the event proxy to add a unique listener to each event on the root node document, and then to find the real trigger target 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 function, which is the basic principle of 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 (IE9 and above) can use the standard-compliant API, including Stoppropagation (), Preventdefault (), and so on. It is also fully supported for event bubbling (bubble) and capturing (capture) modes.

Now let's do a demo to use the following events under JSX:

var Input = React.createclass ({  getinitialstate:function () {    return {value: ' hello! '};  },  Handlechange:function (event) {    this.setstate ({value:event.target.value});  },  render:function () {    var value = This.state.value;    Return (      <div>        <input type= "text" Value={value} onchange={this.handlechange}/>        <p >{value}</p>      </div>    );  }}); React.render (<input/>, document.getElementById ("demo"));

As above is an input box, when we continue to input the value of the box,<p> the contents of the label will also follow the change;

Back to Top

How to use styles in JSX

Most of the time we are writing to the CSS file, but sometimes we can also write style to JSX, the use of styles in JSX and the real style is very similar, but also by the style attribute, but unlike the real DOM, the property value can not be a string, and must be an object, such as the following:

<div style={{color: ' #ff0000 ', fontSize: ' 14px '}}>hello world.</div>

We can see the double curly braces used in jsx, in fact the meaning of the first curly brace is the syntax of JSX, the meaning of the second curly brace is an object; we can also write as follows:

var style = {

Color: ' #ff0000 ',

FontSize: ' 14px '

};

<div style={style}>helloworld.</div>

Reactjs Introduction II

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.