React component
In this section we'll discuss how to use components to make our applications easier to manage.
Next we encapsulate an output of "Hello World!" A component called HelloMessage:
var HelloMessage = React.createClass({ render: function() { return <h1>Hello World!</h1>; } }); ReactDOM.render( <HelloMessage />, document.getElementById('example') );
Instance resolution:
The React.createClass method is used to generate a component class, HelloMessage.
HelloMessage /> Instance component class and output information.
Note that native HTML element names begin with lowercase letters, while custom React class names begin with capital letters, such as HelloMessage, which cannot be written as helloMessage. In addition, it is important to note that the component class can only contain one top-level label, otherwise errors will also be reported.
If we need to pass parameters to the component, we can use the this.props object, as follows:
var HelloMessage = React.createClass({ render: function() { return <h1>Hello {this.props.name}</h1>; } }); ReactDOM.render( <HelloMessage name="W3CSchool" />, document.getElementById('example') );
The name property in the above instance is this.props.name the file.
Note that when you add a property, the class property needs to be written as className, and the for property needs to be written as htmlFor because class and for are reserved words for JavaScript.
Composite components
We can create multiple components to synthesize a component that separates the different functional points of the component.
The following examples enable us to implement components that output the name and URL of the site:
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> ); } });ReactDOM.render(
<WebSite name="W3Cschool教程" site=" https://www.w3cschool.cn" />, document.getElementById('example') );
The WebSite component in the instance uses the Name and Link components to output the corresponding information, which means that WebSite owns instances of Name and Link.