React Introductory Example Tutorial
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 the answer").
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 12 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. DEMO13 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 three libraries: React.js, React-dom.js, and browser.js, which must be loaded first. Among them, React.js is the core library of react, React-dom.js is to provide DOM-related functions, the role of Browser.js is to convert the JSX syntax to JavaScript syntax, this step is very time-consuming, in fact, the line should be placed 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, Reactdom.render ()
Reactdom.render is the most basic method of React for converting a template to an HTML language and inserting a specified DOM node.
ReactDOM.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‘];ReactDOM.render( <div> { names.map(function (name) { return <div>Hello, {name}!</div> }) } </div>, document.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> { React.Children.map(this.props.children, function (child) { return
{Child}
; }) } </ol> ); }});ReactDOM.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 there are three possible values for This.props.children: If the current component has no child nodes, it is undefined; if there is a child node, the data type is object, and if there are multiple child nodes, the data type is array. So be careful when dealing with This.props.children.
React provides a tool method React.children to handle This.props.children. We can use React.Children.map to traverse the child nodes without worrying about whether the This.props.children data type is undefined or object. For more React.children methods, please refer to the official documentation.
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
The aboveMytitlecomponent has atitleproperty. Proptypes tells React that the title property is required, and that its value must be a string. Now, we settitlethe value of the property to a number.
var data = 123;ReactDOM.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".
Seven, get the real DOM node
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 ref attribute (see DEMO07).
var MyComponent = React.createClass({ handleClick: function() { 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> ); }});ReactDOM.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] will return this true DOM node.
It is important to note that due to the this.refs. The [RefName] property gets the real DOM, so you must wait until the virtual DOM is inserted into the document before you can use this property, or you will get an error. In the above code, by specifying the callback function for the Click event for the component, it ensures that the this.refs is not read until the Click event occurs in the real DOM. [RefName] property.
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} this. Click to toggle. </p> ); }});ReactDOM.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> ); }});ReactDOM.render(<Input/>, 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 -= .05; 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> ); }});ReactDOM.render( <Hello name="world"/>, document.body);
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 way a component'sstyleproperties are set 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: ‘‘ }; }, componentDidMount: function() { $.get(this.props.source, function(result) { var lastGist = result[0]; if (this.isMounted()) { this.setState({ 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}>here</a>. </div> ); }});ReactDOM.render( <UserGist source="https://api.github.com/users/octocat/gists" />, document.body);
The above code uses JQuery to complete the Ajax request for illustrative purposes. React itself has no dependencies, and can use other libraries without jquery.
We can even pass a promise object to the component, see Demo12.
ReactDOM.render( <RepoList promise={$.getJSON(‘https://api.github.com/search/repositories?q=javascript&sort=stars‘)} />, document.body);
The above code fetches the data from the GitHub API and then passes the Promise object as a property to the Repolist component.
If the Promise object is fetching data (pending state), the component displays "Loading", if the Promise object is error (rejected status), the component displays an error message, and if the Promise object fetches the data successfully (fulfilled state), The component displays the obtained data.
var repolist = React.createclass ({getinitialstate:function () {return {loading:true, error:null, data:null}; }, Componentdidmount () {This.props.promise.then (value = = This.setstate ({loading:false, data:value}), Error = This.setstate ({loading:false, error:error})); }, Render:function () {if (this.state.loading) {return <span>Loading...</span>; } else if (This.state.error!== null) {return <span>error: {this.state.error.message}</span>; } else {var repos = This.state.data.items; var repolist = Repos.map (function (repo) {return (<li> <a href={repo.html_url}>{r Epo.name}</a> ({Repo.stargazers_count} stars) <br/> {repo.description} </li>); }); Return (<main>
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
Transferred from: http://www.ruanyifeng.com/blog/2015/03/react.html
React Introductory Example Tutorial