React components

In this section we will discuss how to use components to make our applications easier to manage.
Next we encapsulate a component that outputs "Hello World!" With the component name HelloMessage:

React instance

Var HelloMessage = React . CreateClass ( { Render : function ( ) { Return < h1 > Hello World ! </ H1 >; } } ) ; ReactDOM . Render ( < HelloMessage />, document . GetElementById ( ' example ' ) ) ;

try it"

Example Analysis:

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, and custom React class names begin with uppercase letters, such as HelloMessage, which can not be written as helloMessage. In addition to the need to pay attention to the component class can only contain a top-level label, or will be error.
If we need to pass parameters to the component , you can use this.props object, examples are as follows:

React instance

Var HelloMessage = React . CreateClass ( { Render : function ( ) { Return < h1 > Hello { This . Props . Name } </ h1 >; } } ) ; ReactDOM . Render ( < HelloMessage Name = " Runoob " />, document . GetElementById ( ' example ' ) ) ;

try it"
The name attribute in the above example is obtained by this.props.name.
Note that when adding attributes, the class attribute needs to be written as className, and the for attribute needs to be written as htmlFor, because the class and for are reserved words for JavaScript.

Composite components

We can create multiple components to create a component, that is, the components of the different functional points to separate.
The following example we implement the output site name and URL components:

React instance

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 = " rookie tutorial " Site = " http://www.runoob.com " />, document . GetElementById ( ' example ' ) ) ;

try it"
In the example, the WebSite component uses the Name and Link components to output the corresponding information, that is, WebSite has instances of Name and Link.


EmoticonEmoticon