React Getting Started Tutorial

Source: Internet
Author: User
Tags bind html page html tags min
First, React installation
1. React requires the introduction of three libraries:
react.min.js-React's core library react-dom.min.js-Provides DOM-related functions babel.min.js / browser.min.js-Babel can convert ES6 code to ES5 code, which is embedded Support for JSX. 2.Use create-react-app to quickly build a React development environment
create-react-app is from Facebook. With this command, we can quickly build a React development environment without configuration.
The project created by create-react-app is based on Webpack + ES6.
Execute the following command to create the project:
$ cnpm install -g create-react-app
$ create-react-app my-app
$ cd my-app /
$ npm start
HTML page templates
<! DOCTYPE html>
<html>
  <head>
    <script src = "../ build / react.js"> </ script>
    <script src = "../ build / react-dom.js"> </ script>
    <script src = "../ build / browser.min.js"> </ script>
  </ head>
  <body>
    <div id = "example"> </ div>
    <script type = "text / babel">
      // ** Our code goes here! **
    </ script>
  </ body>
</ html>
Note: The purpose of Browser.js is to convert JSX syntax to JavaScript syntax.
$ babel src --out-dir build
The above command can syntactically convert the js files in the src subdirectory, and all the transcoded files are placed in the build subdirectory.
ReactDOM.render ()
ReactDOM.render is the most basic method of React. It is used to convert the template into HTML language and insert the specified DOM node.
ReactDOM.render (
  <h1> Hello, world! </ h1>,
  document.getElementById ('example')
);
The above code inserts an h1 header into the example node
Fourth, JSX syntax
JSX syntax allows HTML to be mixed with JavaScript:
var names = ['Alice', 'Emily', 'Kate'];
ReactDOM.render (
  <div>
  {
    names.map (function (name) {
      return <div> Hello, {name}! </ div>
    })
  }
  </ div>,
  document.getElementById ('example')
);
The above code reflects the basic syntax rules of JSX: when encountering HTML tags (beginning with <), they are parsed using HTML rules; when encountering code blocks (beginning with {), they are parsed using JavaScript rules.
JSX allows JavaScript variables to be inserted directly into templates. If the variable is an array, all members of the array are expanded:
var arr = [
  <h1> Hello world! </ h1>,
  <h2> React is awesome </ h2>,
];
ReactDOM.render (
  <div> {arr} </ div>,
  document.getElementById ('example')
);
Five, components
React allows you to package your code into a component and then insert it into a web page just like you would insert a normal HTML tag.
The React.createClass method is used to generate a component class:
var HelloMessage = React.createClass ({
  render: function () {
    return <h1> Hello {this.props.name} </ h1>;
  }
});

ReactDOM.render (
  <HelloMessage name = "John" />,
  document.getElementById ('example')
);
In the above code, the variable HelloMessage is a component class. When the template inserts <HelloMessage />, an instance of HelloMessage is automatically generated. All component classes must have their own render methods for outputting components.
Note: The first letter of the component class must be capitalized, otherwise an error will be reported. In addition, the component class can only contain a top-level tag, otherwise an error will be reported.
The usage of the component is exactly the same as the native HTML tag. You can add attributes arbitrarily, such as <HelloMessage name = "John">. The HelloMessage component adds a name attribute with a value of John. Component properties can be obtained on the this.props object of the component class. For example, the name property can be read through this.props.name.
Note: When adding component attributes, the class attribute needs to be written as className and the for attribute needs to be written as htmlFor because class and for are reserved words for JavaScript.
Six, this.props.children
The properties of the this.props object correspond to the properties of the component, with one exception, the this.props.children property. It represents all child nodes of the component.
var NotesList = React.createClass ({
  render: function () {
    return (
      <ol>
      {
        React.Children.map (this.props.children, function (child) {
          return <li> {child} </ li>;
        })
      }
      </ ol>
    );
  }
});


ReactDOM.render (
  <NotesList>
    <span> hello </ span>
    <span> world </ span>
  </ NotesList>,
  document.body
);
The NoteList component of the above code has two span children, both of which can be read via this.props.children.
Note: There are three possible values for this.props.children (if the current component has no child nodes, it is undefined; if there is a child node, the data type is object; if there are multiple child nodes, the data type is array).
React provides a utility method React.Children to handle this.props.children. We can use React.Children.map to iterate through the children without worrying about whether the data type of this.props.children is undefined or object.
Seven, PropTypes
Component properties can accept arbitrary values, including strings, objects, functions, and so on. Sometimes, we need a mechanism to verify that the parameters provided by others when using the component meet the requirements.
The PropTypes property of the component class is used to verify whether the properties of the component instance meet the requirements.
var MyTitle = React.createClass ({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },

  render: function () {
     return <h1> {this.props.title} </ h1>;
   }
});
The Mytitle component above has a title property. PropTypes tell React that the title property is required and its value must be a string.
In addition, the getDefaultProps method can be used to set default values for component properties.
var MyTitle = React.createClass ({
  getDefaultProps: function () {
    return {
      title: 'Hello World'
    };
  },

  render: function () {
     return <h1> {this.props.title} </ h1>;
   }
});

ReactDOM.render (
  <MyTitle />,
  document.body
);
The above code will output "Hello World".
Get real DOM nodes
A component is not a real DOM node, but a data structure that exists in memory, called a virtual DOM. Only when it is inserted into the document does it become the real DOM. According to the design of React, all DOM changes occur on the virtual DOM first, and then the actual changes are reflected on the real DOM. This algorithm is called DOM diff, which can greatly improve the performance of web pages.
However, sometimes you need to get the real DOM node from the component, and then you need to use the ref attribute.
var MyComponent = React.createClass ({
  handleClick: function () {
    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>
    );
  }
});


ReactDOM.render (
  <MyComponent />,
  document.getElementById ('example')
);
In the above code, the child node of the component MyComponent has a text input box for getting user input. At this time, you must obtain the real DOM node. The virtual DOM cannot get user input. To do this, the text input box must have a ref attribute, and then this.refs. [RefName] will return this real DOM node.
Note: Because this.refs. [RefName] property gets the real DOM, you must wait until the virtual DOM is inserted into the document before using this property, otherwise an error will be reported.
Nine, this.state
Components inevitably need to interact with users. One of React's innovations is to treat components as a state machine. At the beginning, there is an initial state, and then the user interacts, causing the state to change, which triggers the UI to re-render.
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 {text} this.
Click to toggle.
      </ p>
    );
  }
});


ReactDOM.render (
  <LikeButton />,
  document.getElementById ('example')
);
The above code is a LikeButton component, and its getInitialState method is used to define the initial state, which is an object that can be read through the this.state property. When the user clicks on the component, causing the state to change, the this.setState method modifies the state value. After each modification, this.render method is automatically called to render the component again.
Note: Since this.props and this.state are both used to describe the characteristics of the component, it may cause confusion. A simple way to distinguish is that this.props represents properties that will not change once defined, and this.state is a property that changes with user interaction.
Ten forms
The content that the user fills in the form belongs to the interaction between the user and the component, so it cannot be read with this.props.
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>
    );
  }
});

ReactDOM.render (<Input />, document.body);
In the above code, the value of the text input box cannot be read with this.props.value. Instead, you must define a callback function for the onChange event and read the value entered by the user through event.target.value. This is the case for textarea elements, select elements, and radio elements.
Eleven, the life cycle of components
The life cycle of a component is divided into three states:
Mounting: inserted into the real DOM Updating: being re-rendered Unmounting: removed from the real DOM React provides two processing functions for each state, the will function is called before entering the state, the did function is called after entering the state, three states A total of five processing functions.
componentWillMount () componentDidMount () componentWillUpdate (object nextProps, object nextState) componentDidUpdate (object prevProps, object prevState) componentWillUnmount () In addition, React provides two special state processing functions.
componentWillReceiveProps (object nextProps): called when the loaded component receives new parameters shouldComponentUpdate (object nextProps, object nextState): called when the component determines whether to re-render
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>
    );
  }
});


ReactDOM.render (
  <Hello name = "world" />,
  document.body
);
The above code sets a timer through the componentDidMount method after the hello component is loaded, and resets the transparency of the component every 100 milliseconds, which causes re-rendering.
Note: The setting method of the component's style property cannot be written as style = "opacity: {this.state.opacity};", but must be written as style = {{opacity: this.state.opacity}}, because React component style is An object, so the first major bracket indicates that this is JavaScript syntax, and the second major bracket indicates a style object.
Twelve, Ajax
The component data source is usually obtained from the server through Ajax requests. You can use the componentDidMount method to set the Ajax request. After the request is successful, use this.setState method to re-render the UI.
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 last gist is
        <a href={this.state.lastGistUrl}> here </a>.
      </ div>
    );
  }
});

ReactDOM.render (
  <UserGist source = "https://api.github.com/users/octocat/gists" />,
  document.body
);
We can also pass a Promise object to the component:
ReactDOM.render (
  <RepoList
    promise = {$ .getJSON ('https://api.github.com/search/repositories?q=javascript&sort=stars')}
  />,
  document.body
);
The above code grabs data from Github's API, then passes the Promise object as a property to the RepoList component.
If the Promise object is fetching data (pending state), the component displays "Loading"; if the Promise object reports an error (rejected state), the component displays an error message; if the Promise object successfully fetches data (fulfilled state), the component displays the acquired data .
var RepoList = React.createClass ({
  getInitialState: function () {
    return {loading: true, error: null, data: null};
  },

  componentDidMount () {
    this.props.promise.then (
      value => this.setState ((loading: false, data: value)),
      error => this.setState ((loading: false, error: error)));
  },

  render: function () {
    if (this.state.loading) {
      return <span> Loading ... </ span>;
    }
    else if (this.state.error! == null) {
      return <span> Error: {this.state.error.message} </ span>;
    }
    else {
      var repos = this.state.data.items;
      var repoList = repos.map (function (repo) {
        return (
          <li>
            <a href={repo.html_url}> {repo.name} </a> ({repo.stargazers_count} stars) <br /> {repo.description}
          </ li>
        );
      });
      return (
        <main>
          <h1> Most Popular JavaScript Projects in Github </ h1>
          <ol> {repoList} </ ol>
        </ main>
      );
    }
  }
});
Reprinted from: Click to open the link 
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.