React Series (i): React introduction

Source: Internet
Author: User

React introduction 1. Origin

React is a library of JS components that Facebook has developed to build the front-end interface, and because of the powerful background behind it, this library has no problem with technology development.

Advantages of 2.React

Solve the problem that data change becomes difficult to operate in large-scale project development;

Component development, making development faster;

One-way data flow to help find problems;

Virtual DOM, within the react a set of diff algorithm can quickly calculate the overall need to change the location, so as to achieve rapid local refresh; for a chestnut: delete a list and insert a new table, the calculation will be compared and then inserted;

Jsx compilation method, the HTML code and JS mixed together to write, the component structure is clear, the data structure is clear, then can be converted to JS by the tool.

3. Development methods

The use of react development can be as usual development, the last JSX conversion can be, in the 0.14,react split, so we need to introduce three files

 <  script  src  = ". /js/react.js " ></ script  Span style= "color: #0000ff;" >>  <  script  SRC  = "... /js/react-dom.js " ></ script  >  <  script  src  = ". /js/jsxtransformer.js " ></  Script  >  

The first one does not explain, the second file is to convert the react structure into HTML after inserting into the specified DOM node, the third is the conversion file, the JSX format converted to JS format files. Of course, we normally need to introduce the components we write (if you don't write the components directly in HTML = =#)

Another way of development is based on node environment development, with WEBPACK,GULP to build a set of automated building tools, while in node development we can also cooperate with Babel using ES6 syntax to write, here is not elaborate.

Basic Syntax 1. Hello World

All language learning begins with the phrase we are familiar with-the need to use reactdom.render when converting react to HTML structure

Reactdom.render (        ));

Insert the previously introduced JS and this JSX file can open the browser to see ~

You can see that the first parameter in Reactdom.render is the incoming component, the second parameter is added to a tag, and note that it is generally best not to add it directly to Document.body.

2. Preparation of components

But this is obviously 108,000 miles from the component we're talking about, a simple example of a simple top-down structure where we can split it into three parts (and, of course, more, the simplest of all), then we need to write 3 components, where the head and bottom can be reused in many locations throughout the station. So let's start writing our components:

  

varHeader =React.createclass ({render:function() {        return    }});varMain =React.createclass ({render:function() {        return(<div classname= "Main_box" >     )}});varFooter =React.createclass ({render:function() {        return(<div> <p> Contact phone 1333333333</p> <p>QQ:6843521463</p> </div>    )}});varIndex =React.createclass ({render:function() {        return(<div>     )}}); Reactdom.render (<index/>, document.getElementById (' Div1 '));

Here we first define 3 components using the React.createclass method, then package three components together in the index component and add them to the Domrender.

It should be noted that the code structure in render if it is multi-layered, the outermost layer must be wrapped in a label, otherwise it will be an error.

The name you define must begin with a capital letter.

3.props

Prop passes data in the current component, the common case is that the parent is passed to the child data, which is then called by the child.

varListcontent =React.createclass ({render:function(){        return (            <div> <div>{ This.props.json.one}</div> <div>{ This.props.json.two}</div> </div>        ); }});varall =React.createclass ({render:function(){        varJSON = {                ' One ': ' This is a thing written in react ',                ' Both ': ' Hello World ',        }; return (            <div> <listcontent Json={json}/> </div>        ); }}); Reactdom.render (<all/>,document.getelementbyid (' box '));

Here we define a data in all and then pass it into the listcontent component, and this time the listcontent has JSON data. In the inside of the content structure can use This.props to call, it should be noted that in the tag inserted content needs to be wrapped up with {}.

4.state

React can be considered a large state machine, where the data changes are almost all derived from the state of change, the state can be used to set the status, when triggered by an action to change it to update the page related data. A simple example:

  

varListcontent =React.createclass ({getinitialstate:function() {        return{click:true        }; }, ShowName:function() {         This. SetState ({click:false        }); Alert (' Iceblue ')}, Render:function() {return (             < div > < button disabled={this.state.click} OnClick = { This. ShowName} > Display name </button> </div >        ); }}); Reactdom.render (< listcontent/>, document.getElementById (' box '));

In the initial environment we use getinitialstate (fixed name) to set the initial state value, of course, can not be set. Here we set a status of click, our idea is that after clicking the button becomes non-clickable. Here we define a showname (custom) function to do two things, display the name and change the state, and note that it is best to not add other function codes in the function that alters the state, here for the sake of convenience. This time when we trigger the onclick (fixed) event to invoke the previously defined function and change the click Value by SetState, the component receives the change and changes the page.

Some simple component development can be done basically through props and state.

5.map

Similar to the JQ map, you can traverse the child nodes and do the corresponding operations, we can use the map to reduce the number of duplicated code, only need to change the data filled in it.

var number = [' 1 ', ' 2 ', ' 3 ', ' 4 ']; Reactdom.render (  <div>    {        number.map(name,key) {             return <div key={key}> this year has {name} months </div>        })    }  </div>  document.getElementById (' box '));
6.ref

At the very beginning, we mentioned that the biggest feature of react is the virtual DOM, which means that the component we create is not actually a node, but it becomes the real DOM only when the insert is complete. When the state changes, the finished structure is displayed on the page. If we need to get a real DOM node, we need to use the ref attribute.

varMyComponent =React.createclass ({handleclick:function() {Console.log ( This. Refs.mytextinput); }, Render:function() {           return (                   <div> <input type= "text" ref= "mytextinput" value= "write casually"/> <inp UT type= "button" value= "Print" onclick={ This. Handleclick}/> </div>           )}}); Reactdom.render (<mycomponent/>,document.getelementbyid (' box '));
<input type= "text" value= "casually write" data-reactid= ". 0.0"/>

This is first defined in the first input, ref, then can get to the real node and the corresponding operation, where Data-reactid, similar to the DOM layered identity, you can let react clearly know the DOM structure and make a quick calculation.

7. Life cycle

The so-called life cycle is that we can do different things at different stages of the code operation, in which there are generally several (fixed names):

  getinitialstate: called once before the component is mounted. The return value will be the initial value of the this.state.

Componentwillmount: Both the server side and the client are called only once, and are called immediately before the render execution is initialized. If you call Setstate,render () within this method, you will perceive the updated state, executing only once

  Componentdidmount: called immediately after the initialization of the rendering execution, only the client is valid (the server side is not called). At this point in the life cycle, the component has a DOM representation, and you can get the corresponding DOM node through This.getdomnode ().

There are more ways to update components
  Componentwillreceiveprops: Called when the component receives a new props. When the rendering is initialized, the method does not invoke the

  shouldcomponentupdate: called before a new props or state is received and will be rendered. This method does not invoke when the rendering is initialized

  componentwillupdate: perform some actions when state changes

8. Event name

Touch Event: Ontouchcancel\ontouchend\ontouchmove\ontouchstart

Keyboard events: Onkeydown\onkeypress\onkeyup

Cut Event: Oncopy\oncut\onpaste

Form event: Onchange\oninput\onsubmit

Focus Event: Onfocus\onblur

UI elements: Onscroll (mobile device is finger scrolling and PC mouse sliding)

Scrolling events: Onwheel (mouse wheel)

Mouse Type: Onclick\oncontextmenu (right-click) \ondoubleclick\onmousedown\onmouseenter\ Onmouseleave\onmousemove\onmouseout\onmouseover\onmouseup Ondrag\ondrop\ondragend\ondragenter\ondragexit\ondragleave\ondragover\ondragstart

9. Code Writing considerations

  Style:

    Passing data in react is mentioned before to wrap it in {}, so it is passed inside the tag.

    Class:classname={fontcolor} or Classname= "Class1"

Style:style={{color: "Red"}} or Style={newstyle}, where NewStyle is a defined collection of styles {corlor: "Red", Height: ...}

  Logic:

If you want to insert code in react, you can write outside of the code block, such as

var MyComponent = React.createclass ({        if(...) { do something};         function () {           return  (                   <div>1</div>           )}});

 

Write these today, in the future may be some about webpack or redux combined with React blog, but Bo master is lazy, not necessarily when = =#, finally attach the Chinese API address:

Http://reactjs.cn/react/docs/getting-started.html

  

  

  

React Series (i): React introduction

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.