[Translation] React Getting Started Guide and react Getting Started Guide

Source: Internet
Author: User

[Translation] React Getting Started Guide and react Getting Started Guide

Original article: The React Quick Start Guide

This article briefly introduces how to use ReactJS for development. I will introduce some basic knowledge without in-depth analysis. You can read this article by combining the code. Update: This article has been translated into Portuguese by Hugo Bessa.

Concepts

React has few APIs that are easy to understand and use. Before getting started, I will introduce several concepts one by one.

React ElementIs a JavaScript Object represented as an HTML element. They do not actually exist in the browser. They eventually behave likeh1,divOrsectionAnd other browser elements.

JSXIs a technology used to create React elements and components. For exampleIs a React element written with JSX. It can also be written in pure JavaScriptReact.DOM.h1(null, 'Hello');. It is easier to read and write JSX, and JSX statements must be converted into JavaScript statements before they are released.

Virtual DOMIs a JavaScript tree structure object composed of React elements and components. React renders the virtual DOM into a browser and turns it into a final user interface. React observes changes in the virtual DOM and automatically renders the changes to the browser.

After understanding the above concepts, we can start to use React to write some examples. A series of functions will be developed below. Each example is improved based on the previous example. We will write a photo stream program similar to instagram-No better sample program than this.

Rendering

The first step is to render a virtual element (React element or component ). Note: The virtual element only exists in the memory and must be explicitly told to render it to the browser.

React.render(, document.body)

View JSBin

renderThe function receives two parameters: Virtual element and real browser DOM element. React inserts a virtual element into the specified DOM element. In the preceding example, the image is rendered.

Component)

Components are the essence of React. They are custom React elements and usually have some functions and structure definitions.

var Photo = React.createClass({  render: function() {    return   }});React.render(<Photo />, document.body);

View JSBin

createClassThe function receives an object, which implementsrenderMethod.

ThisPhotoThe component defines<Photo />And render it to document. body.

This component is no different from the previous rendered image, but it lays the foundation for adding custom functions in the future.

Property (Props)

Attributes can be viewed as configuration parameters of components, which look very similar to HTML attributes.

var Photo = React.createClass({  render: function() {    return (      <div className='photo'>                <span>{this.props.caption}</span>        </div>    );    }});React.render(<Photo imageURL='http://tinyurl.com/lkevsb9' caption='Hong Kong!' />, document.body);

View JSBin

imageURLAndcaptionTwo attributes are passedPhotoComponentsrenderFunction.

imageURLUsed in React image elementssrcAttribute,captionUsed as text within the React span element.

Components do not change their attributes, but they remain static. If a component contains dynamic data, a State object is used.

Status)

A status object is used to record data that may change at any time.

var Photo = React.createClass({  toggleLiked: function() {    this.setState({      liked: !this.state.liked    });  },  getInitialState: function() {    return {      liked: false    };  },  render: function() {    var buttonClass = this.state.liked ? 'active' : '';    return (      <div className='photo'>                <div className='bar'>          <button onClick={this.toggoleLiked} className={buttonClass}>                      </button>          <span>{this.props.caption}</span>        </div>      </div>    );  }});React.render(<Photo src='http://tinyurl.com/lkevsb9' caption='Hong Kong!') />, document.body);

View JSBin

The component Status introduces some complexity to the component.

This component has a new function.getInitialState. When the component is initialized, React will call this function. Set the initial state of the component based on the object it returns (as indicated by the function name ).

This component has another new function.toggleLiked. It callssetStateTo switchliked.

InrenderThere isbuttonClassAccordinglikedStatus is marked as 'active' or null.

buttonClassThe class name used as the React button element. This button alsotoggleLikedFunction bindingonClickEvent.

Let's see what the rendering works in the browser:
-Triggered when a button in the component is clickedtoggleLikedFunction
-likedStatus changed
-React: Re-render virtual DOM
-Comparison between new and old virtual DOM
-React identifies the changed part and renders it to the browser.

The previous example shows how to click the button to change the class name.

Composition)

Link some small components to form a large composite component. For examplePhotoComponents can be used inPhotoGalleryComponent, as follows:

var Photo = React.createClass({  toggleLiked: function() {    this.setState({      liked: !this.state.liked    });  },  getInitialState: function() {    return {      liked: false    };  },  render: function() {    var buttonClass = this.state.liked ? 'active' : '';    return (      <div className='photo'>                <div className='bar'>          <button onClick={this.toggleLiked} className={buttonClass}>                      </button>          <span>{this.props.caption}</span>        </div>      </div>    );  }});var PhotoGallery = React.createClass({  render: function() {    var photos = this.props.photos.map(function(photo) {      return <Photo src={photo.url} caption={photo.caption} />    });    return (      <div className='photo-gallery'>        {photos}      </div>    );  }});var data = [  {    url: 'http://tinyurl.com/lkevsb9',    caption: 'Hong Kong!'  },  {    url: 'http://tinyurl.com/mxkwh56',    caption: 'Cows'  },  {    url: 'http://tinyurl.com/nc7jv28',    caption: 'Scooters'  }];React.render(<PhotoGallery photos={data} />, document.body);

View JSBin

PhotoComponents are no different from previous ones. New componentPhotoGalleryThree false data entries are generated.PhotoComponent.

Conclusion

This article is just an introduction to React. I strongly recommend that you read the React official document, which contains all the details you want.

There are also some video resources worth watching. Pete Hunt's re-thinking web application architecture with React and Tom Occhino's React Native for building native mobile applications with React (WIP ).

This article does not describe how to set up your local development environment. The official documentation provides related introductions. Alternatively, you can refer to my solution boilerplate.

If there are any errors in this article, contact me on twitter or submit a pull request to me. Please email me as much as you like.

P.S-if you are developing a more complex React application, we recommend The Flux Quick Start Guide.

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.