React has become a complete set of back-and-forth Web APP solutions. The derivative React Native project, the goal is magnificent, wants to write the Web app the way to write Native app. If it does, the entire Internet industry will be subverted, because the same group of people will be able to run the server, the browser and the phone at the same time with only one UI to write.
Since react is so popular, looks hopeful, of course, should learn it well. From a technical point of view, can satisfy the curiosity, raise the technical level, from the professional angle, is advantageous to the job search and the promotion, facilitates participates in the potential big project. However, a good react tutorial is not easy to find, because this technology is too new, just beginning to become popular, we have no experience, still groping; on the other hand because the react itself is still changing, the API has been adjusting, has not released version 1.0.
When I study react, I am very distressed. Some tutorials discuss some of the details and are not helpful for getting started; some tutorials are good, but shorter, and do not help to see the whole picture. I learned from off and on for a few months, read more than 20 tutorials, in the process, will be helpful to their own Demo are collected, made a library react Demos.
Next, I'll write a comprehensive and understandable react introductory tutorial based on this library. You only need to follow each Demo to do it again, you can grasp the initial react. Of course, the prerequisite is that you have basic JavaScript and DOM knowledge, but you will find that the react requires very little preparation knowledge when you finish reading.
0, installation
React installation package, you can go to the official website https://facebook.github.io/react/downloads.html download. However, react Demos has its own react source code, do not install another, just copy the library to your hard drive on the line.
$ git clone git@github.com:ruanyf/react-demos.git
If you don't have git installed, download the ZIP compression package directly.
The following 10 examples to explain in each Demo subdirectory, each directory has a index.html file, in the browser to open the file (in most cases double-click), you can immediately see the effect.
It should be explained that react can be run in the browser or run on the server, but this tutorial only covers browsers. On the one hand is to try to keep simple, on the other hand react syntax is consistent, server usage and browser is not very different. DEMO11 is the server's first screen rendering example, interested friends can see the source of their own.
One, HTML template
Use React Web page source code, the structure is roughly as follows.
<! DOCTYPE html>
<script src= ". /build/react.js "></script>
<script src= ". /build/jsxtransformer.js "></script>
<body>
<div id= "Example" ></div>
<script type= "TEXT/JSX" >
* * Our code goes here! **
</script>
</body>
The above code has two places to pay attention to. First, the Type property of the last script label is TEXT/JSX. This is because react's unique JSX syntax is incompatible with JavaScript. Wherever you use JSX, add type= "TEXT/JSX".
Second, REACT provides two libraries: React.js and Jsxtransformer.js, which must be loaded first. Among them, the role of Jsxtransformer.js is to convert JSX syntax into JavaScript syntax. This step is very time-consuming, in fact, when the line, it should be put to the server complete.
$ JSX src/build/
The above command can be the SRC subdirectory of the JS file syntax conversion, the file after the transcoding all put in the build subdirectory.
Second, React.render ()
React.render is the most basic method of react, which is used to convert a template into an HTML language and insert a specified DOM node.
React.render (
document.getElementById (' example ')
);
The above code will be a H1 header, insert example node (view demo01), run the following results.
Third, JSX grammar
The code in the previous section, the HTML language written directly in the JavaScript language, without any quotes, is the JSX syntax that allows HTML to be mixed with JavaScript (see DEMO02).
var names = [' Alice ', ' Emily ', ' Kate '];
React.render (
<div>
{
Names.map (function (name) {
Return <div>hello, {name}!</div>
})
}
</div>,
document.getElementById (' example ')
);
The code above embodies the basic grammatical rules of JSX: When you encounter HTML tags (starting with <), you parse them with HTML rules, and when you encounter a block of code (beginning with {), you parse it with JavaScript rules. The results of the above code run as follows.
JSX allows JavaScript variables to be inserted directly in the template. If the variable is an array, all members of the array are expanded (see DEMO03).
var arr = [
];
React.render (
<div>{arr}</div>,
document.getElementById (' example ')
);
The arr variable of the above code is an array, and as a result JSX will add all its members to the template and run the results as follows.
IV. Components
React allows 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 }
});
React.render (
document.getElementById (' example ')
);
In the code above, 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 you can optionally add attributes, 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 class and for are reserved words for JavaScript.
Five, This.props.children
The properties of the This.props object correspond to the component's property one by one, but one exception is the This.props.children property. It represents all the 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, which can be read by This.props.children and run as follows.
Note here, only when the child nodes redundant 1, This.props.children is an array, otherwise it can not use the map method, will be an error.
VI. React.finddomnode ()
The component is not a real DOM node, but 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 react's design, all DOM changes occur first on the virtual DOM, and then the actual change is reflected on the real DOM, which is called Dom diff, which can greatly improve the performance of the Web page.
However, sometimes you need to get the real DOM node from the component, and then use the React.finddomnode method (see DEMO06).
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 (' example ')
);
In the code above, the child nodes of the component mycomponent have a text input box to get the user's input. You must get the real DOM node and the virtual DOM will not get the user input. To do this, the text input box must have a ref attribute and then this.refs. [RefName] points to the child node of the virtual Dom and finally gets the node of the real Dom through the React.finddomnode method.
It is important to note that because the React.finddomnode method gets the real DOM, you must wait until the virtual DOM is inserted into the document to use this method, or null will be returned. The code above, by specifying the callback function for the Click event for the component, ensures that the React.finddomnode method is not invoked until the real DOM has a click event.
React components support a number of events, in addition to the Click event, there are KeyDown, Copy, Scroll, and so on, complete list of events please check the official documentation.
Http://facebook.github.io/react/docs/events.html#supported-events
Seven, This.state
Components are unavoidable to interact with the user, one of the great innovations of react is to see the component as a state machine, start with an initial state, and then interact with the user, causing the state to change, triggering a rendering of the UI (see DEMO07).
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 are {text} this. Click to toggle.
</p>
);
}
});
React.render (
<likebutton/>
document.getElementById (' example ')
);
The code above 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 status value, automatically calls the This.render method, and renders the component again after each modification.
Because both This.props and this.state are used to describe the attributes of a component, confusion can occur. A simple distinction is that this.props represents an attribute that is no longer changed once defined, and This.state is a feature that changes as the user interacts.
Eight, form
The content that the user fills in the form is the interaction between the user and the component, so it cannot be read with This.props (view demo08).
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.body);
In the code above, the value of the text input box cannot be read with This.props.value, and a callback function that defines a OnChange event is used to read the value entered by the user through the Event.target.value. This is the case for textarea elements, select elements, Radio elements, and for more information, please refer to the official documentation.
Ix. component Life cycle
The life cycle of a component is divided into three states:
Mounting: The real DOM has been inserted
Updating: is being rendered again
Unmounting: The real DOM has been moved
REACT provides two processing functions for each State, the will function is invoked before entering the state, the DID function is invoked after the entry state, and three states total five processing functions.
Componentwillmount ()
Componentdidmount ()
Componentwillupdate (Object Nextprops, Object nextstate)
Componentdidupdate (Object Prevprops, Object prevstate)
Componentwillunmount ()
In addition, react also provides two special state processing functions.
Componentwillreceiveprops (Object Nextprops): Called when a loaded component receives a new parameter
Shouldcomponentupdate (Object Nextprops, Object Nextstate): component determines whether to be called when rendering
A detailed description of these methods can be used to refer to the official documentation. Here is an example (see DEMO09).
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>
);
}
});
React.render (
Document.body
);
The code above, after the Hello component is loaded, sets a timer through the Componentdidmount method, resets the transparency of the component every 100 milliseconds, causing the rendering to be rendered again.
In addition, the style property of the component is set up in a way that is also noteworthy and cannot be written
Style= "opacity:{this.state.opacity};"
But to write
Style={{opacity:this.state.opacity}}
This is because the React component style is an object, so the first major bracket indicates that this is a JavaScript syntax, and the second major bracket represents a style object.
10, Ajax
The data source of the component, usually obtained from the server via an AJAX request, can be set up with an AJAX request using the Componentdidmount method, wait until the request succeeds, and then this.setstate the UI (view demo10) again with the method.
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 gist is
<a Href={this.state.lastgisturl}>here</a>
</div>
);
}
});
React.render (
<usergist source= "Https://api.github.com/users/octocat/gists"/>
Document.body
);
The code above uses JQuery to complete the Ajax request, which is for illustration purposes. React without any dependencies, you can use other libraries entirely.