React Introductory Example Tutorial

Source: Internet
Author: User

Nanyi


Date: March 31, 2015


Now the hottest front-end frame is undoubtedly React.


Last week, React Native, based on the React, was released, resulting in a 5000-star acquisition within a day, as evidenced by the level of attention.


React originated in Facebook's internal project because the company was dissatisfied with all the JavaScript MVC frameworks on the market and decided to write a set of Web sites that would be used to erect Instagram. After doing it, found that this set of things very useful, in May 2013, open source.






Because React's design ideas are extremely unique, revolutionary and innovative, the code logic is simple. Therefore, more and more people are beginning to pay attention to and use, think it may be the mainstream tool of WEB development in the future.


The project itself is getting bigger and larger, from the earliest UI engine to a full range of front-end Web App solutions. Derivative of the React Native project, the goal is more magnificent, want to write a Web app to write the Native app. If it can be achieved, the entire Internet industry will be subverted, because the same group of people only need to write once the UI, it can run at the same time on the server, browser and mobile phone (see "Perhaps, DOM is not da ANF)."






Since React is so hot and looks hopeful, of course, you should learn it well. From a technical point of view, curiosity can be met to improve the technical level, from a professional point of view, conducive to job hunting and promotion, to participate in the potential of large projects. However, the good React tutorial is not easy to find, because this technology is too new, has just begun to become popular, we all have no experience, still groping, on the other hand because the React itself is constantly changing, API has been adjusted, has not released 1.0 version.






When I studied React, I was very distressed. Some tutorials discuss some of the details, not helpful for getting started, some tutorials are well written, but shorter, and do not help to see the whole picture. I have been learning for several months on and off, and I have seen more than 20 tutorials, and in this process, I have collected the Demo that will help you, and made a library React Demos.






Below, I will write a comprehensive and understandable React introductory tutorial based on this library. You only need to follow each Demo to do it once, you can master React first. Of course, you have to have basic JavaScript and DOM knowledge, but when you're done reading it, you'll find that React's requirements are really small.


0. Installation


React installation package, can be downloaded to the official website. However, React Demos has come with React source code, no additional installation, just copy this library to your hard drive on the line.


$ git clone [email protected]:ruanyf/react-demos.git
If you don't have git installed, download the zip archive directly.






Here are 11 examples to be explained in each Demo subdirectory, each directory has a index.html file, in the browser open this file (in most cases, double-click), you can immediately see the effect.


It is necessary to note that React can be run in a browser or on a server, but this tutorial only covers browsers. On the one hand is to try to keep simple, on the other hand the React syntax is consistent, server usage and browser is not very different. DEMO11 is the server first screen rendering example, interested friends can go to see the source.


First, HTML templates


The use of React Web source, the structure is roughly as follows.


<! DOCTYPE html> The above code has two places to be aware of. First, the Type property of the last script tag is Text/babel. This is because React's unique JSX syntax is incompatible with JavaScript. Wherever the use of JSX, all should add Type= "Text/babel".


Second, the above code altogether uses two libraries: React.js and Browser.js, which must be loaded first. Among them, the role of Browser.js is to convert JSX syntax to JavaScript syntax. This step is very time consuming, in fact the line should be put on the server to complete.


$ babel src--out-dir Build
The above command can be the SRC subdirectory of the JS file syntax conversion, transcoded files are all placed in the build subdirectory.


Second, React.render ()


React.render is the most basic method of React for converting a template to an HTML language and inserting a specified DOM node.


React.render (The above code will insert a H1 header into the example node (view demo01) and run the result as follows.






Third, JSX grammar


In the previous section of the code, the HTML language is written directly in the JavaScript language without any quotation marks, which is the syntax of JSX, which allows the HTML to be mixed with JavaScript (view Demo02).


var names = [' Alice ', ' Emily ', ' Kate ']; React.render (<div> {names.map (function (name) {return <div>hello, {name}!</div>})} </div> Cument.getelementbyid (' example '));
The above code embodies the basic syntax of JSX: The HTML tags (starting with <) are parsed with HTML rules, and code blocks (beginning with {) are parsed with JavaScript rules. The result of the above code is as follows.






JSX allows JavaScript variables to be inserted directly into the template. If the variable is an array, all the members of the array will be expanded (see DEMO03).


var arr = [The arr variable of the above code is an array, and the result JSX will add all its members to the template, running the result as follows.






Iv. components


React allows the code to be encapsulated as a component (component) and then inserted into a Web page like a normal HTML tag. The React.createclass method is used to generate a component Class (view demo04).


var hellomessage = React.createclass ({render:function () {return In the above code, the variable hellomessage is a component class. When a template is inserted into

The usage of the component is exactly the same as the native HTML tag and can be arbitrarily added to the attribute, such as





To add component properties, one place to note is that the class attribute needs to be written as ClassName, and the for property needs to be written as htmlfor because the class and for are reserved words for JavaScript.


Wu, This.props.children


The properties of the This.props object correspond to the component's property one by one, but with one exception, the This.props.children property. It represents all child nodes of the component (view demo05).


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.body);
The Notelist component of the above code has two span subnodes, all of which can be read by This.props.children and run as follows.






It is important to note that This.props.children is an array only if the child node is 1 extra, otherwise it is not possible to use the map method to make an error.


Liu, Proptypes


A component's properties can accept any value, such as strings, objects, functions, and so on. Sometimes, we need a mechanism to verify that when someone uses a component, the supplied parameters meet the requirements.


The Proptypes property of the component class is used to verify that the properties of the component instance meet the requirements (see DEMO06).


var MyTitle = React.createclass ({proptypes: {title:React.PropTypes.string.isRequired,}, Render:function () {return &L t;h1> {This.props.title} The MyTitle component above has a title property. Proptypes tells React that the title property is required, and that its value must be a string. Now, we set the value of the title property to be a number.


var data = 123; React.render (<mytitle title={data}/>, document.body);
This way, the title property is not validated. The console displays a single line of error messages.


warning:failed proptype:invalid prop ' title ' of type ' number ' supplied to ' MyTitle ', expected ' string '.
For more proptypes settings, you can view official documents.


In addition, the Getdefaultprops method can be used to set default values for component properties.


var MyTitle = React.createclass ({getdefaultprops:function () {return {title: ' Hello World '};}, Render:function () {return The above code will output "Hello world".


Vii. React.finddomnode ()


A component is not a real DOM node, but rather a data structure that exists in memory, called the virtual Dom. Only when it is inserted into the document will it become the real DOM. According to the design of React, all DOM changes occur first on the virtual DOM, and then the actual changes are reflected in the real DOM, which is called Dom diff, which can greatly improve the performance of the Web page.


However, sometimes it is necessary to get the node of the real DOM from the component, then use the React.finddomnode method (see DEMO07).


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= "Foc us the text input "Onclick={this.handleclick}/> </div>); } }); React.render (<mycomponent/>, document.getElementById (' example '));
In the code above, the child nodes of the component mycomponent have a text input box to get the user's input. At this point, the real DOM node must be obtained, and the virtual DOM cannot be entered by the user. In order to do this, the text input box must have a ref attribute and then this.refs. [RefName] points to the child nodes of the virtual DOM, and finally gets the nodes of the real DOM through the React.finddomnode method.


It is important to note that since the React.finddomnode method obtains the real DOM, it must wait until the virtual DOM is inserted into the document before it can be used, otherwise it will return null. In the above code, the React.finddomnode method is called only after the click event of the real DOM has been specified by specifying the callback function for the Click event for the component.


React components support A number of events, in addition to the Click event, there are KeyDown, Copy, Scroll, etc., the complete list of events please check the official documentation.


Eight, This.state


Components inevitably interact with users, and React's innovation is to see components as a state machine, start with an initial state, and then interact with the user, resulting in state changes that trigger a re-rendering of the UI (view demo08).


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 (' example '));
The above code is a Likebutton component whose Getinitialstate method is used to define the initial state, which is an object that can be read by the This.state property. When the user clicks on the component, causing the state to change, the This.setstate method modifies the state value and, after each modification, automatically calls the This.render method to render the component again.


Because both This.props and this.state are used to describe the characteristics of a component, confusion can occur. A simple way to differentiate is that This.props represents features that are not changed once defined, whereas This.state is a feature that changes as the user interacts.


Ix. Forms


The user fills in the form the content, belongs to the user interacts with the component, therefore cannot read with This.props (view demo9).


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 (&LT;INPUT/&GT;, document.body);
In the above code, the value of the text input box cannot be read with This.props.value, but to define a callback function for the OnChange event to read the user input value by Event.target.value. TextArea elements, select elements, radio elements are all in this case, for more information refer to the official documentation.


X. Life cycle of components


The life cycle of a component is divided into three states:


Mounting: The real DOM is inserted
Updating: is being re-rendered
Unmounting: The real DOM has been removed
React provides two processing functions for each State, the will function is called before it enters the state, and the DID function is called after it enters the state, with three states totaling five processing functions.


Componentwillmount ()
Componentdidmount ()
Componentwillupdate (Object Nextprops, Object nextstate)
Componentdidupdate (Object Prevprops, Object prevstate)
Componentwillunmount ()
In addition, the REACT provides two special state processing functions.


Componentwillreceiveprops (Object Nextprops): Called when a loaded component receives a new parameter
Shouldcomponentupdate (Object Nextprops, Object nextstate): Called when the component determines whether to re-render
For a detailed description of these methods, you can refer to the official documentation. Here is an example (see DEMO10).


var Hello = React.createclass ({getinitialstate:function () {return {opacity:1.0};}, Componentdidmount:function () {This.timer = setinterval (function () {var opacity = this.state.opacity; opacity-=; if (opacity < 0.1) {opacity = 1.0; } this.setstate ({opacity:opacity}); }.bind (this), 100); }, Render:function () {return (<div style={{opacity:this.state.opacity}}> Hello {this.props.name} </div>) ; } }); React.render (The above code, after the Hello component is loaded, sets a timer through the Componentdidmount method, which re-sets the transparency of the component every 100 milliseconds, causing a re-render.


In addition, the style property of the component is set in a way that is also noteworthy and cannot be written


Style= "opacity:{this.state.opacity};"
and to write


Style={{opacity:this.state.opacity}}
This is because the React component style is an object, so the first significant parenthesis indicates that this is the JavaScript syntax, and the second significant parenthesis represents the style object.


Xi. Ajax


The data source of the component, usually obtained from the server via an AJAX request, can be set by using the Componentdidmount method, waiting for the request to succeed, and then using the This.setstate method to re-render the UI (view demo11).


var usergist = React.createclass ({getinitialstate:function () {return {username: ', Lastgisturl: '};}, Componentdid Mount:function () {$.get (This.props.source, function (result) {var lastgist = result[0]; if (this.ismounted ()) {This.set State ({username:lastGist.owner.login, lastGistUrl:lastGist.html_url}); }}.bind (this)); }, Render:function () {return (<div> {this.state.username} ' s last gist is <a href={this.state.lastgisturl}>h Ere</a>. </div>); } }); React.render (<usergist source= "https://api.github.com/users/octocat/gists"/&GT;, document.body);
The above code uses JQuery to complete the Ajax request for illustrative purposes. React has no dependencies and can use other libraries entirely.


12. Reference Links


React ' s official site
React ' s official examples
React (Virtual) DOM terminology, by Sebastian Markb?ge
The React Quick Start Guide, by Jack Callister
Learning React.js:Getting Started and concepts, by Ken Wheeler
Getting started with React, by Ryan Clark
React JS Tutorial and the Gotchas, by Justin Deal
React Primer, by Binary Muse
JQuery versus React.js thinking, by Zigomir
Finish

React Introductory Example Tutorial

Related Article

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.