Latest web development tutorials

React assembly

This chapter we will discuss how to use components to make our application easier to manage.

Next, we encapsulate an output "! Hello World" component, component called HelloMessage:

var HelloMessage = React.createClass({
  render: function() {
    return <h1>Hello World!</h1>;
  }
});

ReactDOM.render(
  <HelloMessage />,
  document.getElementById('example')
);

try it"

Analysis examples:

React.createClass method for generating a component class HelloMessage.

<HelloMessage /> instance of a component class and output information.

Note that the native HTML element names begin with a lowercase letter, and custom React class names begin with a capital letter, for example, can not be written HelloMessage helloMessage. Note that in addition to the component class can contain only one top-level tag, or else will be given.

If we need to pass parameters to a component, you can usethis.props object instance as follows:

var HelloMessage = React.createClass({
  render: function() {
    return <h1>Hello {this.props.name}</h1>;
  }
});

ReactDOM.render(
  <HelloMessage name="w3big" />,
  document.getElementById('example')
);

try it"

The above example by this.props.namename attribute to get.

Note that when you add attributes, class attributes to be written className, for property to be written htmlFor, this is because the class and for the JavaScript reserved words.


Composite Components

We can create multiple components into one component, namely the different functional components of the separation point.

The following examples we achieved output site name and URL components:

var WebSite = React.createClass({
  render: function() {
    return (
      <div>
        <Name name={this.props.name} />
        <Link site={this.props.site} />
      </div>
    );
  }
});

var Name = React.createClass({
  render: function() {
    return (
      <h1>{this.props.name}</h1>
    );
  }
});

var Link = React.createClass({
  render: function() {
    return (
      <a href={this.props.site}>
        {this.props.site}
      </a>
    );
  }
});

React.render(
  <WebSite name="本教程" site=" http://www.w3big.com" />,
  document.getElementById('example')
);

try it"

Examples of components used in WebSite Name and Link components to the output of the corresponding information, that has WebSite instance of Name and Link.