Super-Power JavaScript React Framework Introductory Tutorial _ Basics

Source: Internet
Author: User
Tags bind

React is the skeleton of a group of cattle x farmers in Facebook. Implements a virtual DOM, using DOM to add the required component seconds and eliminate unnecessary seconds. React plays the role of V in the MVC structure, but if you Flux with it, you have a very nice frame that makes M and V easy to sync, and Flux.
components are

In react, you can create a feature-specific component that you can't find in an HTML element, such as the Drop-down navigation in this tutorial. Each component has its own site (scope), so we define a component that can be reused over and over again, and there is no need to interact with other components at all!

Each component has a function called Render, which can be efficiently returned to the HTML that is to be shot to the browser. We can also call react's other components, which means that this one into the react deep like the sea, Oh, no, is only unexpected, nothing can be done.

JSX

If you often pay attention to react you may find something called JSX. JSX allows us to write HTML in JavaScript, rather than include JavaScript in HTML. It can help us develop quickly because we don't have to worry about string and line wrapping. You can run jsx in the browser, but it's not recommended, because it slows down your page. Gulp and Grunt provide a JSX interpreter for your preprocessing tasks, so if you want to use JSX, I recommend that this feature be turned on.
using JSX

As mentioned earlier, JSX each component has a render method that produces a "ViewModel (view model)"-you can put the information of this model (ViewModel) into the view before returning HTML to the component, means that your HTML will change dynamically based on this model (for example, a dynamic list).


Once you have completed the operation, you can return what you want to render (render), we use JSX to do is so simple

var examplecomponent = React.createclass ({
  render:function () {return
    (
      <div classname= "navigation") >
        Hello world!
      </div>
      );
  }
);

If you want to run this code in your browser, you'll only get hints of syntax errors, because in JavaScript < and > characters are enclosed in quotes. When you run the JSX interpreter on the code, it will be converted to this

var examplecomponent = React.createclass ({
  render:function () {return
    (
      react.createelement) (' div ', { ClassName: ' Navigation '}, ' Hello world! ')
      ;
  }
);

You can point to this test sample-I'm using the browser JSX interpreter (This is not recommended, but for Jsfiddle).

It's running! Jsx explains all the DOM nodes you have generated using react.createelement, generating node types, parameters, and content. You may not need to jsx, but that means you have to manually write all the DOM nodes outside React.createelement. Countless examples tell me to use JSX.

You must be wondering why I use className on the DOM instead of class. This is because class is a reserved word for JavaScript. When JSX interprets your code, it changes all the attributes on the node to an object, but you can't treat the object as a property!

To use a variable on a property
if you want to dynamically change the component's style class (or any other attribute value), you can use the variable. But you can't just pass in a variable name and you're going to wrap it in a pair of braces so that JSX knows it's 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.
the initial renderer
when you first want to render a react component, you need to tell react what component to render, and an existing DOM node to indicate where to render the component. To do this you will use the 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! You can then invoke other components as usual, or you can use the render function many times if you wish, but you still want to use multiple components if you don't want to use react to render the entire page.

The basis of a component

A component can have its own state. This allows us to reuse the same components multiple times but make them look completely different because the state of each component instance is unique.

These are called attributes when you pass attributes to a component. Instead of just being limited to HTML attributes, you can pass anything you want to pass and access it through this.props within the component. This allows us to reuse the same components but pass a different set of attributes, such as "Configuration" of the component.
Property

According to our front "Hello world!" example, we have className properties on the HTML node. Inside the component, we can use This.props.classname to access this value, but as mentioned above, you can pass anything you like. For our drop down, we need to configure the navigation as an object, and the component will use it as a configuration to render. 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 we can access this.props.config now, we will be subjected to an empty array (the Navigationconfig value). Let's explain the status before we get into the real navigation code.

State

As discussed earlier, each component has its own "state". When you want to use the state, you define the initial state so that you can use This.setstate to update the state. Whenever the state is updated, the component calls the render function again, replacing or altering the value previously rendered, with a new value. This is the mystery of the virtual DOM-the algorithm for computing differences is really react internally, so we don't have to go back to the DOM update (because DOM is slow). React calculates the variance and produces a collection of instructions (for example, by joining the "active" class to "Navigation__link" or removing a node) and executing them on the DOM.

Using navigation, we open the Drop-down menu to remain in the state. To do this, add a getinitialstate function to the class configuration object and return the object with the initial state we want.

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 have set it to 1. When we are ready to open a drop-down menu, we will use the position of the navigation item in the configuration array in the state, and because the array index starts at 0, we have to use-one means that the navigation item has not yet been pointed.

We can use This.state to access the state, so if we go to observe atthis.state.openDropdown, there should be 1 to be returned.

Life cycle of components

Each component has its "lifecycle"-a series of functions you can define in the component configuration that will be invoked during the life cycle of the part. We've seen the getinitialstate. One it is called only once, when the component is mounted.
Componentwillmount

This function is invoked when the component is to be mounted. This means that we can run the necessary code for component functionality here. Because render is called multiple times in the component lifecycle, we typically place code that needs to be executed once, such as a XHR request.

var examplecomponent = React.createclass ({
  componentwillmount:function () {
    //XHR request here to get data
  }  ,
  render:function () {
    //This gets called many The times in a Components life return
    (
      <div>
        Hello world!
      </div>
      );
  }
);

Componentdidmount

Once your component has run the render function and actually renders the component into the DOM, the Componentdidmount is invoked. We can do whatever DOM we need to do here, and we've got anything that needs to depend on what the component actually does in the DOM, like rendering a chart. You can access the DOM node internally by calling This.getdomnode.

var examplecomponent = React.createclass ({
  componentdidmount:function () {
    var node = This.getdomnode ();
    Render a chart on the DOM node
  } and
  render:function () {return
    (
      <div>
        Hello world!
      </div>
      );
  }
);

Componentwillunmount

If you're ready, this function will be invoked when the component is removed from the DOM. This allows us to clean up behind the components, such as removing any event listeners that we have already bound. If we do not clean up behind ourselves, and when one of the events is triggered, an attempt is made to compute a component that is not loaded, react throws an error.

var examplecomponent = React.createclass ({
  componentwillunmount:function () {
    //Unbind any event listeners SP Ecific
  to the component},
  render:function () {return
    (
      <div>
        Hello world!
      </div>
      );
  }
);

Component methods

React also provides a more convenient way for our components to work. They are invoked during the creation of the component. For example, Getinitialstate allows us to define a default state so that we don't have to worry about whether or not a state item exists in the code for further inspection.
Getdefaultprops

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

When you define a component, these default properties are cached, so that they are the same for each instance of the component and cannot be changed. For the navigation component, we specify the configuration as an empty array, so that no error occurs within the Render method even if there is no incoming configuration.

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 arbitrarily specify a type for each attribute. This is useful for us to examine and handle unexpected assignments of attributes. As the following dropdown, we specify that only arrays can be placed in the configuration.

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

We can also add mixins to the component. This is a basic component independent of react (just a configuration of an object type). This means that if we have two functionally similar components, we can share a configuration (if the initial state is the same). We can create a method abstractly in mixin so that we don't have to write the same code two times.

var examplemixin = {
  componentdidmount:function () {
    //bind some event listeners here
  },
  componentwillu Nmount: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>
      );
  }
);

So all the components have the same Componentdidmount and Componentwillunmount method, saving the code we rewrite. In any case, you cannot override (overwrite) these attributes, and if this property is set in Mixin, it is not covered in this component.

Traversal loops

When we have an array that contains objects, how do we loop through the array and render each object into the list item? JSX allows you to use it in any Javascript file, you can map the array and return JSX, then use react to render it.

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

The navigation configuration consists of arrays and objects, including an HREF attribute that points to a hyperlink and a text property for display. When we map, it will go through this array in turn to get the object. We can access href and text and use it in HTML. When the list is returned, the list items in the array are replaced, so when we put it in the react, it will know how to render it!

Mixed

To the current position, we have done all the dropdown list expansion. We need to know which item is being down and we will use the. Children attribute to traverse our navigationconfig array. Next, we can use the loop to manipulate the Drop-down child element entries.

var navigationconfig = [{href: ' http://ryanclark.me ', text: ' My Website ', children: [{HRE 
        F: ' 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.ar
    Ray}, 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 Classna
                Me= "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);

Examples are here-but we can still see the entry down, although we have opendropdown set to be-1.

We can tell if the drop is open by accessing this.state in the component, and we can add a new CSS style class to show the effect of the mouse hover.

var navigationconfig = [{href: ' http://ryanclark.me ', text: ' My Website ', children: [{HRE 
        F: ' 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.sets
  Tate ({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.ope Ndropdown.bind (this, index)}> <a classname= "Navigation__link" href={item.href-}> {item.t
    Ext} </a> {dropdown} </li>);
    }, this); Return (<div classname= "NaviGation "> {items} </div>);
}
});
 React.render (<navigation config={navigationconfig}/>, document.body);

Here to see the example-the mouse across the "My Website", the dropdown will show.


In the front, I've added a mouse event to each list item. As you can see, I'm using. Bind (BIND) calls, not other ways to invoke-this is because, when the user's mouse delimits the area of the element, we do not care where the cursor is, all we need to know is that the dropdown is turned off, so we can set its value to 1. What we need to know, however, is what element is pulled down when the user clicks the mouse, so we need to be aware of the parameter (the index of the element). We use bindings to invoke rather than simply through functions (function) because we need to invoke it through react. If we call directly, then we need to call all the time instead of calling him in the event.

Now we can add a lot of entries to the Navigationconfig, and we can add them to the feature. View the instance.

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.