Reactjs Getting Started

Source: Internet
Author: User

Reactjs Getting Started learning a

Read Catalogue

    • What is react?
    • React how do I make a component?
    • Understanding Component Properties Props
    • Understand how the data is rendered in the page
    • Understanding the data obtained from the server side and understanding the state
Back to Top

What is react?

React is only the view layer, and we often see angular is a complete framework, and react is not, so we see that their two focus is different, so we can not compare, react provides template syntax and some function hooks for the rendering of HTML, only for the view layer.

What are the advantages of react?

1. Virtual DOM

When the state of the DOM tree changes, the virtual DOM mechanism compares the front and back dom trees, and if the two dom trees have different locations, then react only responds to the DOM modifications for the different areas, which is the react's higher performance is achieved using virtual DOM.

2. Data Flow

REACT implements a one-way response data stream, which reduces duplicate code, which is why it is simpler than traditional data binding.

browser support for react: ie9-The following browsers are not supported for react.

Now let's learn the basic use of react!

First of all, react is good at component pages, let's take a look at how to use react to render the page, as follows:

First you need to introduce react.js on the page

<script src= "./build/react.min.js" ></script>

The HTML code is structured as follows:

<div id= "Content" ></div>

The JS code is as follows:

<script>        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 ("content")        ; </script >

Generate the code structure on the page as follows:

Take effect under ie9+ Firefox chrome;

Let's explain what the above code means:

React.createclass (): the method to create a new React component, the most important of which is render, which returns a React component tree, which will be rendered as HTML;

The div tag above is not a real DOM node, they are instances of the React div component, we can think of react is through this to how to handle the tag or some data, react is safe, it does not generate HTML strings, so the default block XSS attacks;

React.render (): The method is to instantiate the root component, start the framework, which has a second parameter, meaning: Inject markup into the original DOM element;

React is not dependent on jquery, so above is the second parameter of React.render () by document.getElementById ("content"), and of course we can use Jqeury as the second argument, But we must do the following:("#content") [0], not ("#content");

Back to Top

React how do I make a component?

We have a website page: The homepage is divided into the following blocks, navigation page, sidebar, and content area; If I want to navigate the page now, the sidebar and content area are all made up of a component module because there are a lot of pages that need to be common; page structure diagram:

So below we can use the React.createclass () method to create a react component, the following code:

The navigation page code is as follows: We use JSX to write code as follows: (Remember that the page needs to be introduced)

<script src= "./build/react.min.js" ></script>

<script src= "./build/jsxtransformer2.js" ></script>

This code is currently tested, convenient point directly introduced;

<script type= "TEXT/JSX" >/* Navigation module code */var Navmode = React.createclass ({render:function () { return (<div className = "Navlist" > Hello word!            I am a Nav List </div>);        }        });                    /* Side Bar Module code */var Slidemode = React.createclass ({render:function () {return ( <div classname= "Slidemode" >hello world!        I am a slide</div>)});                    /* Content Area Module code */var Contentmode = React.createclass ({render:function () {return ( <div classname= "Contentmode" >hello world!        I am comtent</div>)});                    /* Page DIV package above three modules */var page = React.createclass ({render:function () {return ( <div classname= "Homepage" >                       

After the page rendering is complete, look at the following demo:

As a result, the preview effect is also visible on the page, and the JSX compiler automatically rewrites the HTML tag as a react.createelement (tagName) expression by blending HTML tags to create our components based on JSX syntax.

Back to Top

Understanding Component Properties Props

Props represents the properties of the component itself, some of the attributes or data that the parent node passes to the child layer node, such as my code above, the content area, and possibly different modules with different contents, so we need to have the same template Contentmode Different content is displayed depending on the delivery of the parameters:

/* Content Area module code */var Contentmode = React.createclass ({        render:function () {            return (                <div classname=) Contentmode "><div class=" Contents ">{this.props.contents}</div>                    {This.props.children}                </div>            )        });/* Page div package above three modules */var page = React.createclass ({    render:function () {        return (            <div classname= "homepage" >                <contentmode  contents = "Longen" >this is one comment</ Contentmode >                <contentmode  contents = "Longen2" >this is the Comment</contentmode >            < /div>            )        });/* Initialize into content container */react.render (    react.createelement (page,null), document.getElementById ("content"));

The DOM structure shown in the page is as follows:

As above, we pass from the parent node page to the child node Contentmode some data, the data passed from the parent node to the child node is called "props";

In Jsx, a JavaScript expression is placed in curly braces (as attributes or child nodes); We access the named property passed to the component as the key of the this.props , any inline element as a This.props.children;

Back to Top

Understand how the data is rendered in the page

such as the AJAX request to return data, and now my side is the simulation of static data: The following return data:

var data = [{' Name ': ' Longen1 ', ' age ': ' + '},{' name ': ' Longen2 ', ' Age ': 30}];

Now what we are going to do is to render to the content (contents area) by the data above, the first step is to instantiate the root component and call the React.render () method, as follows:

var data = [{' Name ': ' Longen1 ', ' age ': ' + '},{' name ': ' Longen2 ', ' Age ': 30}];

/* Initialize into the content container */react.render (    <contentmode data={data}/>, document.getElementById ("content"); Call contents Area Contentmode module, the code is as follows:/* Content Area module code */var Contentmode = React.createclass ({    render:function () {        return (            < Div classname= "Contentmode" >                

As above we pass the data through the parent node Contentmode to the child node Page,page module through the this.props to fetch the data from the parent node, and then invoke the page module, render the data, the page module renders the following data:

var Page = React.createclass ({    render:function () {        var contentmodes = this.props.data.map (function (content) {            return (                <p classname= "Pline" data-age={content.age}>{content.name}</p>            )        });        Return (            <div classname= "homepage" >{ContentModes}</div>        )    });

The page module then takes a map traversal with its own property, This.props, and shows the effect as follows:

The HTML code renders as structured as follows:

Back to Top

Understanding the data obtained from the server side and understanding the state

Now let's create a new Page.json to store JSON data, with the following data:

[{"Name": "I am the Dragon en I come to test data 1", "Age": "},{" "name": "I am Bugenhua to test Data 2", "Age": "30"}]

Now let's get the data from the server side, we first use the React.render () method to initialize the root component, the following code:

/* Initialize into content container */

React.render (

<contentmode url= "Page.json"/>, document.getElementById ("content")

);

Here is all the code below:

var Page = React.createclass ({render:function () {var contentmodes = This.props.data.map (function (content) {        Return (<p classname= "Pline" data-age={content.age}>{content.name}</p>)        }); Return (<div classname= "homepage" >{ContentModes}</div>)});/* Content Area module Code */var contentmod    E = React.createclass ({getinitialstate:function () {return {data:[]};            }, Componentdidmount:function () {$.ajax ({url:this.props.url, DataType: ' JSON ',            Success:function (data) {this.setstate ({data:data}); }.bind (This), Error:function (Xhr,status,err) {Console.log (this.props.url,status,err.tostring ())            ;    }.bind (This)}); }, Render:function () {return (<div classname= "Contentmode" > 

So far: each of our components has rendered itself according to its own props, props is immutable, they are data passed from the parent node, but if we need to update the data from the server side, we can use state to update the data. this.state is a component-private and we can change it by This.setstate () , then the component will re-render itself.

Now let's analyze the code above:getinitialstate () is executed only once in the component life cycle, setting the initialization state of the component. The method is encapsulated in the react source code.

Componentdidmount () is a component is rendered when react automatically call the method, which is also react source code in the encapsulated, we can see as the above codes in the call getinitialstate () method, an empty array is defined for data []; When calling the Componentdidmount () method, by sending an AJAX request (where we use jquery to demonstrate Ajax), we use this.setstate ({data:data}) when the data is updated; This method assigns values to data rewriting, changes the original data, and then uses the new data to automatically update the UI;

The following results are shown on the page:

The page HTML code renders the following structure:

We can also emulate Sina Weibo, automatically refresh data every few seconds, here we can use simple setinterval () to poll, of course, we can use a better method WebSockets technology

The code is as follows:

<script type= "TEXT/JSX" > var page = react.createclass ({render:function () {var contentmodes = This.props.data.map (function (content) {return (<p classname= "Pline" Data-age={conten            t.age}>{content.name}</p>)});    Return (<div classname= "homepage" >{ContentModes}</div>)});        /* Content Area Module code */var Contentmode = React.createclass ({getinitialstate:function () {return {data:[]}; }, Loadserver:function () {$.ajax ({url:this.props.url, DataType: ' J                Son ', success:function (data) {this.setstate ({data:data}); }.bind (This), Error:function (Xhr,status,err) {Console.log (This.props.url,status,err.tos                Tring ());        }.bind (This)}); }, Componentdidmount:fUnction () {this.loadserver ();        SetInterval (This.loadserver,this.props.pollinterval); }, Render:function () {return (<div classname= "Contentmode" > &L            T;h1> content Rendering in 

As in the code, we make them send Ajax requests every 2 seconds, requesting new data back;

Okay, because of the relationship between the time and the introduction of the first study here, back to continue to learn!

Reactjs Getting Started

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.