Portal: http://www.cnblogs.com/yunfeifei/p/4486125.html
Now the hottest front-end frames are angularjs, React, Bootstrap, and so on. Since contact with Reactjs,reactjs's virtual DOM and the development of the component has attracted me deeply, the following come with me to enjoy Reactjs style bar ~ ~ The article is a bit long, patient read, you will have a great harvest oh ~
I. Introduction of REACTJS
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.
REACTJS website Address: http://facebook.github.io/react/
GitHub Address: Https://github.com/facebook/react
second, the understanding of Reactjs and the advantages of Reactjs
First of all, for react, there are some misunderstanding, here first summed up:
- React is not a complete MVC framework, it can be considered as a V (view) in MVC, and even react does not quite recognize the MVC development model;
- React server-side render capability can only be regarded as a icing on the cake, not its core point of departure, in fact, react official site almost no mention and its application on the server side;
- Some people take react and web Component in the same way, but they are not completely competitive relationship, you can use react to develop a real web Component;
- React is not a new template language, JSX is just a representation, no JSX react can work.
1. Background and principle of Reactjs
In web development, we need to manipulate the DOM in real time by reacting the changed data to the UI. complex or frequent dom operations are often the cause of performance bottlenecks (how high-performance complex DOM operations are often an important metric for measuring a front-end developer's skills). React introduced the virtual DOM mechanism for this purpose: a set of Dom APIs was implemented with JavaScript on the browser side. All DOM constructs are made based on the react, and each time the data changes, react reconstructs the entire DOM tree, then compares the current entire DOM tree with the previous DOM tree to get the difference between the DOM structure, Then only the parts that need to be changed are actually updated in the browser DOM. And react can batch the refresh of the virtual DOM, the two data changes in an event loop are merged, for example, if you change the node contents from a to B successively, and then from B to A,react, the UI does not change, and if you control it manually, This logic is often extremely complex. Although it is necessary to construct a complete virtual DOM tree every time, because the virtual DOM is memory data, the performance is very high, and the actual DOM operation is only the diff part, so it can achieve the purpose of improving performance. In this way, while ensuring performance, developers will no longer need to focus on how changes to one or more specific DOM elements can be updated, but only to be concerned about how the entire interface is being render in any given state of the data.
If you write a Web page of server-side render as you did in the 90 's, you should know that what the server is doing is sending HTML to the browser based on the data. If one of the user's clicks needs to change a state text, it is done by refreshing the entire page. The server side does not need to know which piece of HTML has changed, but simply refreshes the entire page based on the data. In other words, any changes to the UI are done through a whole refresh. Instead, react brings this development model to the front end in a high-performance way, and you can think of refreshing the entire page with every update to the interface. As for how to perform a partial update to ensure performance, this is what the react framework will do.
Using Facebook's example of a chat app in React's video, when a new message comes in, traditional development ideas like, your development process needs to know which data came up, how to add the new DOM node to the current DOM tree, and based on the react of development ideas such as, You always have to care about the data as a whole, and how the UI changes between the two data are completely left to the framework. As you can see, the use of react greatly reduces the complexity of logic, meaning that development is less difficult and there are fewer opportunities for bugs to be generated.
2, the component of
Virtual Dom (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, individually functional UI component. React recommends a component-based rethinking of the UI composition, defining each module that is functionally independent on the UI as a component, and then building the overall UI by composing or nesting the small components into large components. For example, Facebook's instagram.com entire site was developed using react, and the entire page was a large component that contained a large number of other components nested, and it was interesting to see the code behind it.
If the idea of MVC allows you to separate the view-data-controller, then the modular way of thinking is to bring the separation between the UI function modules. We look at the differences between MVC and component development ideas through a typical blog review interface.
For the MVC development model, the developer defines the three as different classes to achieve the separation of performance, data, and control. Developers are more technical in the context of the UI to split, to achieve loose coupling.
For react, it's a completely new approach, with developers starting from a functional perspective, dividing the UI into different components, each packaged individually.
In react, you organize and write your code according to the natural partitioning of the interface module, and for the comment interface, the entire UI is a large component of widgets, each of which cares only for its own part of the logic and is independent of each other.
React that a component should have the following characteristics:
(1) composable (composeable): One component is easy to use with other components or nested inside another component. If another component is created inside a component, then the parent component owns (own) The subcomponents it creates, and with this feature, a complex UI can be split into multiple simple UI components;
(2) Reusable (REUSABLE): Each component is a standalone feature that can be used in multiple UI scenarios;
(3) maintainable (maintainable): Each small component contains only its own logic, which is easier to understand and maintain;
Second, download Reactjs, write Hello,world
Reactjs download is very simple, in order to facilitate everyone to download, here again give http://facebook.github.io/react/downloads.html, download completed, I see is a compressed package. After extracting, we create a new HTML file that references the two JS files of React.js and Jsxtransformer.js. The HTML template is as follows (the JS path is changed to its own):
<! DOCTYPE html>
Here you may wonder why the type of script is TEXT/JSX, because React's unique JSX syntax is incompatible with JavaScript. wherever the use of JSX, all should 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 to JavaScript syntax. This step is very time consuming, in fact the line should be put on the server to complete.
Here we can start to write the code, first of all, we first to understand the Reactjs inside the React.render method:
React.render is the most basic method of React for converting a template to an HTML language and inserting a specified DOM node.
Here we write the code in the script tag to output Hello,world, the code is as follows:
React.render (
It is important to note that react does not rely on jquery, of course we can use jquery, but the second parameter in render must use the JavaScript native getElementById method, and you cannot use jquery to select DOM nodes.
Then, in the browser open this page, you can see the browser display a big hello,world, because we used the
Here, congratulations, you have entered the Reactjs door ~ ~ below, let us further study Reactjs bar ~ ~
Third, JSX grammarHTML language directly in the JavaScript language, without any quotation marks, this is the JSX syntax, which allows the HTML and JavaScript mix, understand the Angularjs see the following code will feel very familiar with, we look at the code:
var names = [' Jack ', ' Tom ', ' Alice ']; React.render ( <div> { names.map (function name) { return <div>hello, {Name}!</div >} ) } </div>, document.getElementById (' container ') );
Here we declare a names array, and then iterate through the front with the hello, output to the DOM, the output 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, with the following code:
var arr = [
The results appear as follows:
The asterisk here is just for logo use, do not be fooled by her ~ ~
You see here, show you to react still very interested in, congratulations to you, persist down, then below, we began to learn react inside of "real kung Fu" ~ ~ is ready?
Iv. Reactjs Components1. Component Properties
As I said earlier, Reactjs is based on component development, so let's start by learning the components inside the Reactjs, React allow the code to be encapsulated as a component (component), and then insert the component in the Web page as you would insert a normal HTML tag. The React.createclass method is used to generate a component class.
Next, let's write the first component greet, have a Name property, and then output the value of the Hello + name, the code is as follows:
var Greet = React.createclass ({ render:function () { return
See this code, contact Angularjs friends are not a familiar feeling, but here are a few things to note:
1, get the value of the property is This.props. Property name
2. The first letter of the component name created must be capitalized.
3. When adding CSS class for elements, use classname.
4. How to set the Style property of a component is also worth noting, write STYLE={{WIDTH:THIS.STATE.WITDH}}
2. Component Status
Components are unavoidable to interact with the user, React's innovation is to consider the component as a state machine, starting with an initial state, and then interacting with the user, resulting in state changes that trigger a re-rendering of the UI. Let's write a small example, a text box and a button that can change the editing state of a text box by clicking the button, preventing editing and allowing editing. Use this example to understand the state mechanism of REACTJS. Look at the code first:
var inputstate = React.createclass ({ getinitialstate:function () { return {enable:false}; }, Handleclick:function (event) { this.setstate ({enable:!this.state.enable}); }, render:function () { return ( <p> <input type= "text" disabled={this.state.enable}/> <button onclick={ This.handleclick}>change state</button> </p> ); } ); React.render ( <inputstate/>, document.getElementById (' container ') );
Here, we also use a method getinitialstate, which executes when the component is initialized and must return null or an object. Here we can access the property value by This.state. Property name, where we will enable this value to bind to the disabled of input, and use the SetState method when you want to modify the property value. We declare the Handleclick method, which binds to the button above, to implement changing the value of state.enable. The effect is as follows:
Principle Analysis:
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.
Here are some noteworthy points:
1. The Getinitialstate function must have a return value, which can be null or an object.
2. The method to access state is this.state. Property name.
3, the variable with {} package, no need to double quotation marks.
3. Component Life cycle
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
Let's look at an example:
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), ( )}, 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.
4. Nesting of components
React is based on component development, so what are the biggest advantages of component development? No doubt, of course, reuse, let's look at how the react in the end of the implementation of the component reuse, here we also write an example, the code is as follows:
var Search = React.createclass ({ render:function {) { return ( <div> {this.props.searchType}: <input type= "text"/> <button>Search</button> </div> ); } ); var Page = react.createclass { render:function () { return ( <div>
Here we create a search component, and then we create a page component, and then we call the search component in the page component, and we call two times, where we pass the value through the property searchtype, and we finally show the result
v. Summary of ReactjsAbout Reactjs today first learned here, the following to summarize, the main points are as follows:
1. Reactjs is based on component development, so ultimately your page should be a large component consisting of several small components.
2, the value can be passed to the inside of the component through the property, the same can be passed through the property of the internal results to the parent component (for everyone to study); To do DOM operations on changes to certain values, place these values in state.
3. When adding an external CSS style to a component, the class name should be written as classname instead of class, and the internal style should be style={{opacity:this.state.opacity} instead of style= "opacity:{ This.state.opacity}; ".
4. The first letter of the component name must be capitalized.
5. The variable name is wrapped with {} and cannot be enclosed in double quotes.
Vi. ReferencesReact Chinese Document http://reactjs.cn/
React Introductory Example Tutorial http://www.ruanyifeng.com/blog/2015/03/react.html
Disruptive front-end UI development framework: React Http://www.infoq.com/cn/articles/subversion-front-end-ui-development-framework-react
I can understand it at a glance. Reactjs Introductory Tutorial-Essence Edition-Reprint