Getting started with the React framework of JavaScript, javascriptreact

Source: Internet
Author: User

Getting started with the React framework of JavaScript, javascriptreact

React is the framework of codoon X, a group of coders in Facebook. A virtual DOM is implemented, and the required components are added in seconds in DOM mode and deleted in seconds that are not needed. React plays the role of V in the MVC structure. However, if you use Flux together, you will have a very good framework that can easily synchronize M and V, let's talk about Flux later ~
Components

In React, you can create a component with special functions, which you cannot find in the HTML element, such as the drop-down navigation in this tutorial. Each component has its own scope. Therefore, after defining a component, we can use it repeatedly and do not need to interact with other components!

Each component has a function called render, which can efficiently return HTML to the browser. We can also call other React components, which means that this entry into React is similar to the sea.

JSX

If you often pay attention to React, you may find something called JSX. JSX allows us to write HTML in Javascript, instead of using HTML to include Javascript. It can help us develop quickly, because we don't have to worry about strings and line breaks. You can run JSX in your browser, but it is not recommended because it slows down your page. Gulp and grunt provide a JSX interpreter for your preprocessing tasks. Therefore, if you want to use JSX, we recommend that you enable this function.
Use JSX

As mentioned above, every JSX component has a render method, which generates a "ViewModel (view model)"-you can set this model (ViewModel) before returning HTML to the component) in the view, it means that your HTML will dynamically change according to this model (for example, a dynamic list ).


Once you complete the operation, you can return what you want to render (render). It is so easy to use JSX.
 

var ExampleComponent = React.createClass({  render: function () {    return (      <div className="navigation">        Hello World!      </div>      );  }});

If you want to run this code in your browser, you will only get a syntax error prompt, because the <and> characters in Javascript must be enclosed in quotation marks. When you run the JSX interpreter on the code, it will be converted
 

var ExampleComponent = React.createClass({  render: function () {    return (      React.createElement('div', {className: 'navigation'}, 'Hello World!')      );  }});

Click here for the test example-I am using the browser JSX interpreter (this is not recommended, but for JSFiddle ).

Running! JSX explains all DOM nodes generated using React. createElement, and generates node types, parameters, and content. You don't need JSX, but this means you have to manually write all DOM nodes other than React. createElement. Countless examples tell me to use JSX.

You must be wondering why I use className instead of class on the DOM. This is because class is a reserved word of Javascript. When JSX interprets your code, it will change all the attributes on this node to an object, but you cannot regard the object as an attribute!

Use variables on Attributes
If you want to dynamically change the style class of the component (or any other attribute value), you can use the variable. however, you cannot just input a variable name. You also need to wrap it with a large arc so that JSX can know that this is an external variable.
 

var ExampleComponent = React.createClass({render: function () {  var navigationClass = 'navigation';  return (    <div className={ navigationClass }>      Hello World!    </div>    );}});

You can see this function here.
Initial Renderer
When you first want to render a React component, you need to tell the React component to render and create an existing DOM node to indicate where to render the component. therefore, you need to use React. render function.
 

var ExampleComponent = React.createClass({render: function () {  return (    <div className="navigation">      Hello World!    </div>    );}});React.render(<ExampleContent />, document.body);

He will render the component on the body node-simple! Now you can call other components as usual, or use the render function many times if you want to, if you don't want to use React to render the entire page, however, you still want to use multiple components.

The basis of a component

A component can have its own "status ". This allows us to use the same components multiple times but makes them look completely different, because the status of each component instance is unique.

These are called attributes when you pass attributes to a component. Not limited to HTML properties, you can pass anything you want to pass and access it through this. props in the component. This allows us to reuse the same component but pass a set of different attributes, such as the "configuration" of the component ".
Attribute

According to the preceding "Hello World !" For example, we have the className attribute on the HTML node. In the component, we can use this. props. classname to access this value, but as described earlier, you can pass anything you like. For the drop-down list, we need to configure the navigation as an object, and the component will use it as the configuration for rendering. Let's get started-
 

var navigationConfig = []; var Navigation = React.createClass({  render: function () {    return (      <div className="navigation">               </div>      );  }});

 
React. render (<Navigation config = {navigationConfig}/>, document. body );

If you can access this. props. config now, we will receive an empty array (value of navigationConfig ). Let's explain the status before we enter the encoding of the real navigation.

Status

As discussed earlier, each component has its own "status ". To use the status, you must define the initial status before using this. setState to update the status. Whenever the status is updated, the component calls the render function again to replace or change the previously rendered value with a new value. This is what the oyi-computing difference algorithm of the virtual DOM is actually done in React, so we don't need to update the DOM (because the DOM is very slow ). React calculates the difference and generates a set of commands (for example, adding to the "navigation _ link" to the "active" class, or removing a node ), and execute them on the DOM.

Use the navigation bar to keep the drop-down menu in the status. To this end, add a getInitialState function to the class configuration object and return the object with the desired initial state.
 

var navigationConfig = []; var Navigation = React.createClass({  getInitialState: function () {    return {      openDropdown: -1    };  },  render: function () {    return (      <div className="navigation">               </div>      );  }}); React.render(<Navigation config={ navigationConfig } />, document.body);

You will find that we set it to-1. When we are going to open a drop-down menu, we will use the position of the navigation item in the configuration array in the status, because the array index starts at 0, we have to use-1 to indicate that there is no navigation item.

We can use this. state to access the status. Therefore, if we observe atthis. state. openDropdown,-1 will be returned.

Component lifecycle

Each component has its own "lifecycle"-this is a series of functions that you can define in the component configuration and they will be called within the lifecycle of the component. We have seen that getinitialstate is called only once and called when the component is mounted.
ComponentWillMount

This function is called when the component is to be mounted. This means that we can run the Code necessary for the component function here. Since the render is called multiple times in the life cycle of the component, we usually put the code that only needs to be executed once here, such as XHR request.
 

var ExampleComponent = React.createClass({  componentWillMount: function () {    // xhr request here to get data  },  render: function () {    // this gets called many times in a components life    return (      <div>        Hello World!      </div>      );  }});

ComponentDidMount

Once your component has run the render function and actually renders the component to the DOM, componentDidMount will be called. Here we can do any DOM operations that need to be done. Anything that can be done only after the component actually exists in the DOM, such as rendering a chart. You can access the DOM node by calling this. getDOMNode internally.
 

var ExampleComponent = React.createClass({  componentDidMount: function () {    var node = this.getDOMNode();    // render a chart on the DOM node  },  render: function () {    return (      <div>        Hello World!      </div>      );  }});

ComponentWillUnmount

If you prepare to remove a component from the DOM, this function will be called. This allows us to clean up the components, such as removing any event listeners we have bound. If we do not clean up behind ourselves, and when an event is triggered, we will try to calculate a component that is not loaded, and React will throw an error.
 

var ExampleComponent = React.createClass({  componentWillUnmount: function () {    // unbind any event listeners specific to this component  },  render: function () {    return (      <div>        Hello World!      </div>      );  }});

Component Method

React also provides components with a more convenient way to work. They are called during component creation. For example, getInitialState allows us to define a default state, so we don't have to worry about whether the status project exists in the Code for further checks.
Getdefaproprops

When we create a component, we can define the default value for the component property according to our ideas. This means that when we call components, if we set values for these properties, the component will have a default "configuration", and we don't have to worry about checking attributes in the next line of code.

When you define a component, these default attributes are cached, so they are the same for each component instance and cannot be changed. For the navigation component, we specify the configuration as an empty array, so no error will occur in the render method even if the configuration is not passed in.
 

var Navigation = React.createClass({  getInitialState: function () {    return {      openDropdown: -1    };  },  getDefaultProps: function () {    return {      config: []    }  },  render: function () {    return (      <div className="navigation">               </div>      );  }});

React.render(<Navigation config={ navigationConfig } />, document.body);

PropTypes

We can also specify the type for each attribute at will. This is very useful for us to check and handle unexpected attribute assignment. As shown in the following dropdown, we specify that only Arrays can be configured.
 

var Navigation = React.createClass({  getInitialState: function () {    return {      openDropdown: -1    };  },  getDefaultProps: function () {    return {      config: []    }  },  propTypes: {    config: React.PropTypes.array  },  render: function () {    return (      <div className="navigation">               </div>      );  }}); React.render(<Navigation config={ navigationConfig } />, document.body);

Mixins

You can also add mixins to components. This is a basic component independent of React (only an object type configuration ). This means that if we have two feature-like components, we can share a configuration (if the initial status is the same ). We can create a method in mixin abstractly, so that we don't need to write the same code twice.
 

var ExampleMixin = {  componentDidMount: function () {    // bind some event listeners here  },  componentWillUnmount: function () {    // unbind those events here!  }}; var ExampleComponent = React.createClass({  mixins: [ExampleMixin],  render: function () {    return (      <div>        Hello World!      </div>      );  }}); var AnotherComponent = React.createClass({  mixins: [ExampleMixin],  render: function () {    return (      <div>        Hello World!      </div>      );  }});

In this way, all components have the same componentDidMount and componentWillUnmount methods, saving the code we have rewritten. In any case, you cannot overwrite these attributes. If this attribute is set in mixin, it cannot be overwritten in this component.

Traversal cycle

When we have an array containing objects, how do we loop through this array and render each object to the list items? JSX allows you to use it in any Javascript file. You can map this array and return JSX, and then use React for rendering.
 

var navigationConfig = [  {    href: 'http://ryanclark.me',    text: 'My Website'  }];var Navigation = React.createClass({  getInitialState: function () {    return {      openDropdown: -1    };  },  getDefaultProps: function () {    return {      config: []    }  },  propTypes: {    config: React.PropTypes.array  },  render: function () {    var config = this.props.config;    var items = config.map(function (item) {      return (        <li className="navigation__item">          <a className="navigation__link" href={ item.href }>            { item.text }          </a>        </li>        );    });    return (      <div className="navigation">        { items }      </div>      );  }});React.render(<Navigation config={ navigationConfig } />, document.body);

Use navigationConfigin in JSFilddle at will

Navigation configuration consists of arrays and objects, including an href attribute pointing to a hyperlink and a text attribute for display. When ing is performed, the object is obtained through the array one by one. We can access href and text and use it in HTML. When the list is returned, the list items in this array will be replaced, so we will know how to render it when we put it into React!

Hybrid editing

By now, we have expanded all the drop-down lists. We need to know which project the project is located. We will use the. children attribute to traverse our navigationConfig array. Next, we can use a loop to operate the drop-down sub-element entries.

var navigationConfig = [  {    href: 'http://ryanclark.me',    text: 'My Website',    children: [      {        href: 'http://ryanclark.me/how-angularjs-implements-dirty-checking/',        text: 'Angular Dirty Checking'      },      {        href: 'http://ryanclark.me/getting-started-with-react/',        text: 'React'      }    ]  }];var Navigation = React.createClass({  getInitialState: function () {    return {      openDropdown: -1    };  },  getDefaultProps: function () {    return {      config: []    }  },  propTypes: {    config: React.PropTypes.array  },  render: function () {    var config = this.props.config;    var items = config.map(function (item) {      var children, dropdown;      if (item.children) {        children = item.children.map(function (child) {          return (            <li className="navigation__dropdown__item">              <a className="navigation__dropdown__link" href={ child.href }>                { child.text }              </a>            </li>          );        });        dropdown = (          <ul className="navigation__dropdown">            { children }          </ul>        );      }      return (        <li className="navigation__item">          <a className="navigation__link" href={ item.href }>            { item.text }          </a>          { dropdown }        </li>        );    });    return (      <div className="navigation">        { items }      </div>      );  }});React.render(<Navigation config={ navigationConfig } />, document.body);

The instance is here-but we can still see the entries, even though we set openDropdown to-1.

We can access this. state in the component to determine whether the drop-down is opened or not, and we can add a new css style class for it to show the effect of the mouse hover.
 

var navigationConfig = [  {    href: 'http://ryanclark.me',    text: 'My Website',    children: [      {        href: 'http://ryanclark.me/how-angularjs-implements-dirty-checking/',        text: 'Angular Dirty Checking'      },      {        href: 'http://ryanclark.me/getting-started-with-react/',        text: 'React'      }    ]  }];var Navigation = React.createClass({  getInitialState: function () {    return {      openDropdown: -1    };  },  getDefaultProps: function () {    return {      config: []    }  },  openDropdown: function (id) {    this.setState({      openDropdown: id    });  },  closeDropdown: function () {    this.setState({      openDropdown: -1    });  },  propTypes: {    config: React.PropTypes.array  },  render: function () {    var config = this.props.config;    var items = config.map(function (item, index) {      var children, dropdown;      if (item.children) {        children = item.children.map(function (child) {          return (            <li className="navigation__dropdown__item">              <a className="navigation__dropdown__link" href={ child.href }>                { child.text }              </a>            </li>          );        });        var dropdownClass = 'navigation__dropdown';        if (this.state.openDropdown === index) {          dropdownClass += ' navigation__dropdown--open';        }        console.log(this.state.openDropdown, index);        dropdown = (          <ul className={ dropdownClass }>            { children }          </ul>        );      }      return (        <li className="navigation__item" onMouseOut={ this.closeDropdown } onMouseOver={ this.openDropdown.bind(this, index) }>          <a className="navigation__link" href={ item.href }>            { item.text }          </a>          { dropdown }        </li>        );    }, this);    return (      <div className="navigation">        { items }      </div>      );  }});React.render(<Navigation config={ navigationConfig } />, document.body);

Here, let's take a look at the instance-move the mouse over "My Website", and the drop-down will show.


Previously, I added a mouse event to each list item. As you can see, I use. bind (binding) call, not other call-this is because when the user's mouse draws an element area, we do not focus on where the cursor is, all we need to know is, close the drop-down, so we can set its value to-1. However, we need to know which element is pulled down and expanded when the user clicks the mouse, so we need to know this parameter (element index ). We use the binding method to call instead of simply calling through a function because we need to call it through React. If we call it directly, we need to call it all the time instead of calling it in the event.

Now we can add a lot of entries to navigationConfig, and we can also add styles to it to function. View instances.

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.