Home > Article > Web Front-end > ReactJs Quick Start Tutorial (Essential Edition)
The most popular front-end frameworks now include AngularJS, React, Bootstrap, etc. Since I came into contact with ReactJS, the virtual DOM (Virtual DOM) and component-based development of ReactJs have deeply attracted me. Let’s experience the style of ReactJs with me~~ The article is a bit long, read it patiently, you will have a great understanding Harvest~
1. Introduction to ReactJS
React originated from Facebook’s internal project. Because the company was not satisfied with all the JavaScript MVC frameworks on the market, it decided to write its own one using Let’s set up the Instagram website. After making it, I found that this set of things is very useful, so it was open sourced in May 2013. Because React's design idea is extremely unique, it is a revolutionary innovation, has outstanding performance, and the code logic is very simple. Therefore, more and more people are beginning to pay attention to and use it, thinking that it may be the mainstream tool for web development in the future.
ReactJS official website address: http://facebook.github.io/react/
Github address: https://github.com/facebook/ react
2. Understanding of ReactJS and the advantages of ReactJS
First of all, there are some misunderstandings about React. Let’s summarize them here:
React is not a complete MVC framework. It can be considered as the V (View) in MVC at most. Even React does not fully recognize the MVC development model;
React’s server-side Render capability can only It’s an icing on the cake, not its core starting point. In fact, the official React website barely mentions its application on the server side;
Some people compare React to Web Component, but the two are not completely competitive. , you can use React to develop a real Web Component;
React is not a new template language, JSX is just a representation, and React can work without JSX.
1. Background and principles of ReactJS
In web development, we always need to reflect changing data to the UI in real time, and then we need to operate the DOM. Complex or frequent DOM operations are usually the cause of performance bottlenecks (how to perform high-performance complex DOM operations is usually an important indicator of a front-end developer's skills). React introduces a virtual DOM (Virtual DOM) mechanism for this purpose: a set of DOM API is implemented on the browser side using Javascript. When developing based on React, all DOM construction is performed through virtual DOM. Whenever the data changes, React will rebuild the entire DOM tree. Then React compares the current entire DOM tree with the previous DOM tree to obtain the DOM structure. Difference, and then only the parts that need to change are updated in the actual browser DOM. Moreover, React can batch refresh the virtual DOM. Two data changes in an event loop (Event Loop) will be merged. For example, if you continuously change the node content from A to B, and then from B to A, React will think that the UI has not changed, and if controlled manually, this logic is usually extremely complicated. Although a complete virtual DOM tree needs to be constructed every time, because the virtual DOM is memory data, the performance is extremely high, and only the Diff part is operated on the actual DOM, thus improving performance. In this way, while ensuring performance, developers no longer need to pay attention to how a certain data change is updated to one or more specific DOM elements, but only need to care about how the entire interface is rendered in any data state.
If you have written a pure Web page with server-side Rendering like you did in the 1990s, you should know that all the server-side has to do is render HTML based on the data and send it to the browser. If a certain status text needs to be changed due to a user click, this can also be done by refreshing the entire page. The server does not need to know which small piece of HTML has changed, but only needs to refresh the entire page based on the data. In other words, any UI changes are done through an overall refresh. React brings this development model to the front end in a high-performance way. Every time you update the interface, you can think that the entire page has been refreshed. As for how to perform partial updates to ensure performance, that is what the React framework has to do.
Borrowing the example of the chat application in Facebook’s video introducing React. When a new message comes, the traditional development idea is as shown above. Your development process needs to know which piece of data has come and how to convert the new DOM The node is added to the current DOM tree; and the development idea based on React is as shown below. You only need to care about the overall data. How the UI changes between the two data is completely left to the framework. It can be seen that using React greatly reduces the logic complexity, which means that development difficulty is reduced and there are fewer opportunities for bugs to occur.
2. Componentization
Virtual DOM (virtual-dom) not only brings simple UI development logic, but also brings the idea of component development. The so-called components are encapsulated UI components with independent functions. React recommends rethinking the composition of the UI in the form of components, defining each module with relatively independent functions on the UI as a component, and then combining small components to form large components through nesting, and finally completing the construction of the overall UI. For example, Facebook's entire instagram.com site is developed using React. The entire page is one large component, which contains a large number of other nested components. If you are interested, you can take a look at the code behind it.
If the idea of MVC allows you to separate the view-data-controller, then the componentized way of thinking brings about the separation between UI functional modules. Let’s look at the difference between MVC and component development ideas through a typical Blog comment interface.
For the MVC development model, developers define the three into different classes to achieve the separation of performance, data, and control. Developers split the UI more from a technical perspective to achieve loose coupling.
For React, it is a completely new idea. From a functional perspective, developers divide the UI into different components, and each component is packaged independently.
In React, you organize and write your code according to the natural division of interface modules. For the comment interface, the entire UI is a large component composed of small components, and each component only cares about itself. Parts of logic are independent of each other.
React believes that a component should have the following characteristics:
(1) Composeable: A component is easy to use with other components, or embedded Inside another component. If a component creates another component inside, then the parent component owns the child component it created. Through this feature, a complex UI can be split into multiple simple UI components;
( 2) Reusable: Each component has independent functions and can be used in multiple UI scenarios;
(3) Maintainable: Each small component only contains Its own logic is easier to understand and maintain;
2. Download ReactJS, write Hello, world
ReactJs download is very simple. In order to facilitate everyone to download, here it is given again The download address is http://facebook.github.io/react/downloads.html. After the download is completed, what we see is a compressed package. After decompression, we create a new html file and reference the two js files react.js and JSXTransformer.js. The html template is as follows (change the js path to your own):
<!DOCTYPE html> <html> <head> <script src="build/react.js"></script> <script src="build/JSXTransformer.js"></script> </head> <body> <div id="container"></div> <script type="text/jsx"> // ** Our code goes here! ** </script> </body> </html>
You may wonder here why the type of script is text/jsx. This is because of React’s unique JSX syntax. Not compatible with JavaScript. Wherever JSX is used, type="text/jsx" must be added. Secondly, React provides two libraries: react.js and JSXTransformer.js, which must be loaded first. Among them, JSXTransformer.js is used to convert JSX syntax into JavaScript syntax. This step is time-consuming, and when it is actually online, it should be completed on the server.
Here we can start writing code. First, let’s get to know the React.render method in ReactJs:
React.render is the most basic method of React, used to convert templates Convert to HTML language and insert the specified DOM node.
Below we write code in the script tag to output Hello and world. The code is as follows:
React.render( <h1>Hello, world!</h1>, document.getElementById('container') );
It should be noted here 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 jQuery cannot be used to select DOM nodes.
Then, when you open this page in the browser, you can see that the browser displays a big Hello, world, because we used the
Here, congratulations, you have entered the door of ReactJS~~Now, let us further learn ReactJs~~
3. Jsx syntax
HTML language Written directly in the JavaScript language without any quotation marks, this is the syntax of JSX, which allows the mixing of HTML and JavaScript. If you know AngularJs, you will feel very familiar when you see the following code. Let's take a 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, then traverse and add Hello in front, and output it to the DOM. The output result is as follows:
JSX allows JavaScript to be inserted directly into the template variable. If this variable is an array, all members of the array will be expanded. The code is as follows:
var arr = [ <h1>Hello world!</h1>, <h2>React is perfect!</h2>, ]; React.render( <div>*{arr}*</div>, document.getElementById('container') );
The display result is as follows:
The asterisk here is just for identification, don’t be confused by it~~
你看到这里,说明你对React还是蛮感兴趣的,恭喜你,坚持下来了,那么下面,我们开始学习React里面的"真功夫"了~~ Are you ready?
四、ReactJS组件
1、组件属性
前面说了,ReactJS是基于组件化的开发,下面我们开始来学习ReactJS里面的组件,React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。React.createClass 方法就用于生成一个组件类。
下面,我们来编写第一个组件Greet,有一个name属性,然后输出hello + name的值,代码如下:
var Greet = React.createClass({ render: function() { return <h1>Hello {this.props.name}</h1>; } }); React.render( <Greet name="Jack" />, document.getElementById('container') );
看到这段代码,接触过AngularJS的朋友们是不是有一种熟悉的感觉,不过这里有几点需要注意:
1、获取属性的值用的是this.props.属性名
2、创建的组件名称首字母必须大写。
3、为元素添加css的class时,要用className.
4、组件的style属性的设置方式也值得注意,要写成style={{width: this.state.witdh}}
2、组件状态
组件免不了要与用户互动,React 的一大创新,就是将组件看成是一个状态机,一开始有一个初始状态,然后用户互动,导致状态变化,从而触发重新渲染 UI 。下面我们来编写一个小例子,一个文本框和一个button,通过点击button可以改变文本框的编辑状态,禁止编辑和允许编辑。通过这个例子来理解ReactJS的状态机制。先看代码:
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') );
这里,我们又使用到了一个方法getInitialState,这个函数在组件初始化的时候执行,必需返回NULL或者一个对象。这里我们可以通过this.state.属性名来访问属性值,这里我们将enable这个值跟input的disabled绑定,当要修改这个属性值时,要使用setState方法。我们声明handleClick方法,来绑定到button上面,实现改变state.enable的值.效果如下:
原理分析:
当用户点击组件,导致状态变化,this.setState 方法就修改状态值,每次修改以后,自动调用 this.render 方法,再次渲染组件。
这里值得注意的几点如下:
1、getInitialState函数必须有返回值,可以是NULL或者一个对象。
2、访问state的方法是this.state.属性名。
3、变量用{}包裹,不需要再加双引号。
3、组件的生命周期
组件的生命周期分成三个状态:
Mounting:已插入真实 DOM
Updating:正在被重新渲染
Unmounting:已移出真实 DOM
React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。
componentWillMount() componentDidMount() componentWillUpdate(object nextProps, object nextState) componentDidUpdate(object prevProps, object prevState) componentWillUnmount()
此外,React 还提供两种特殊状态的处理函数。
componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用
下面来看一个例子:
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( <Hello name="world"/>, document.body );
上面代码在hello组件加载以后,通过 componentDidMount 方法设置一个定时器,每隔100毫秒,就重新设置组件的透明度,从而引发重新渲染。
4、组件的嵌套
React是基于组件化的开发,那么组件化开发最大的优点是什么?毫无疑问,当然是复用,下面我们来看看React中到底是如何实现组件的复用的,这里我们还写一个例子来说吧,代码如下:
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> <h1>Welcome!</h1> <Search searchType="Title" /> <Search searchType="Content" /> </div> ); } }); React.render( <Page />, document.getElementById('container') );
这里我们创建了一个Search组件,然后又创建了一个Page组件,然后我们在Page组件中调用Search组件,并且调用了两次,这里我们通过属性searchType传入值,最终显示结果如图:
五、ReactJs小结
关于ReactJS今天就先学习到这里了,下面来总结一下,主要有以下几点:
1、ReactJs是基于组件化的开发,所以最终你的页面应该是由若干个小组件组成的大组件。
2、可以通过属性,将值传递到组件内部,同理也可以通过属性将内部的结果传递到父级组件(留给大家研究);要对某些值的变化做DOM操作的,要把这些值放到state中。
3. When adding external css styles to components, the class name should be written as className instead of class; when adding internal styles, it 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. Variable names should be wrapped with {} and cannot be enclosed in double quotes.
The above is the ReactJs quick start tutorial (essence version) introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!
For more ReactJs Quick Start Tutorial (Essential Edition) related articles, please pay attention to the PHP Chinese website!