Home > Web Front-end > JS Tutorial > body text

Getting started with React: How to create components in React

不言
Release: 2018-08-22 17:41:50
Original
1481 people have browsed it

Create a component

Before creating a component, please pay attention to the following points:

  1. The first letter of the name of the component must be capitalized

  2. The JSX returned in the component can only be a root node, and all content must be framed by an element

1. Stateless functional component

None Stateful functional components can understand that achievements are generated by a function, making the code more readable, streamlined, convenient, and reducing redundancy. Stateless components have the following characteristics:

  1. The component cannot be instantiated, and the overall rendering is improved

  2. The component cannot access this object because it is not instantiated, so it cannot access this object

  3. Components have no life cycle

  4. Stateless components can only access input props and have no state

import React from 'react'
import { connect } from 'dva';

 function CreateComponent(props) {
   console.log(props);
   return (
     <p>
        <span>{props.name}今年{props.age}岁</span>
     </p>
   )
 }

export default connect(state => ({
  name:'小明',
  age:15
}))(CreateComponent);
Copy after login

2.React.Component class component

Each component class must implement a render method. Special attention should be paid here. This render method must return a JSX element, that is, wrap all content with an outermost element. If it returns a parallel Multiple JSX elements are illegal, as shown below:

import React from 'react'

class CreateComponent extends React.Component {
     render() {
       return(
         <p>
           <h2>标题</h2>
            <ul>
              <li>首先</li>
              <li>其次</li>
              <li>最后</li>
            </ul>
         </p>
       )
     }
}

export default CreateComponent;
Copy after login

The above example is to wrap the h2 element and ul with a p

1. Component event monitoring

import React from 'react'

class CreateComponent extends React.Component {

   clickFunc = (e) => {
     console.log("监听:",e.target.innerHTML);
   }

   clickValue = (value) => {
     console.log(value);
   }
    render() {
      return (
       <p>
         <a onClick={this.clickFunc}>监听事件</a>
         <br/>
         <a onClick={this.clickValue.bind(this,123)}>this对象</a>
      </p>
      )
    }

}

export default CreateComponent;
Copy after login

The above is an example of event monitoring and parameter passing

2. Component state and setState

Usually in a component, state is used to put the status of the internal parameters of the component, and setState is used to change the parameters in the state, for example:

import React from 'react'

class CreateComponent extends React.Component {
  state = {
    flag : true
  }
   clickValue = () => {
     this.setState({
       flag: !this.state.flag
     })
   }
    render() {
      return (
       <p>
         <span>flag的值为:{this.state.flag ? '真' : '假'}</span>
         <br/>
         <button onClick={this.clickValue}>改变flag值</button>
      </p>
      )
    }

}

export default CreateComponent;
Copy after login

3. The props of the component

props are the properties in the component. You cannot change your own props inside the component, such as , create a component, and then call this component in another component, as follows:

import React from 'react';

function NewComponent(props) {
  return (
    <p>
       {props.content}
    </p>
  );
}


export default NewComponent;
Copy after login

Create a component NewComponent, and then call it, as follows:

import React from 'react'
import NewComponent from './newComponent.js'

class CreateComponent extends React.Component {
    render() {
      return (
       <p>
         <NewComponent content={&#39;我是内容&#39;} />
      </p>
      )
    }

}

export default CreateComponent;
Copy after login

It can be seen from here that props are components The attribute values ​​brought in, props actually allow external components to configure themselves, and state is the component's control of its own state.

4. Component life cycle

Constructor component initialization:

constructor initializes some parameter properties, etc.

Before rendering the componentWillMount component:

componentWillMount This function slowly changed after react16.3.0 Deprecated, use componentDidMount instead

componentDidMountAfter component rendering:

componentDidMount is executed after component rendering, and data can be loaded

render component rendering:

render component rendering display page

import React from 'react'

class CreateComponent extends React.Component {
  constructor () {
    super()
    console.log('construct:页面初始化')
  }

  componentWillMount () {
    console.log('componentWillMount:页面将要渲染')
  }

  componentDidMount () {
    console.log('componentDidMount:页面渲染结束')
  }


    render() {
      console.log('render:页面渲染');
      return (
       <p>
         页面渲染
      </p>


      )
    }

}

export default CreateComponent;
Copy after login

Output result:

construct:页面初始化
componentWillMount:页面将要渲染
render:页面渲染
componentDidMount:页面渲染结束
Copy after login
componentWillUnmount component deletion

The componentWillUnmount function is a function that is executed before the component is to be deleted. The following code:

import React from 'react';

class NewComponent extends React.Component {
  componentWillUnmount() {
    console.log('componentWillUnmount:将要从页面中删除');
  }

  render() {
    return (
      <p>
         {this.props.content}
      </p>
    );
  }

}

export default NewComponent;
Copy after login

Create a component NewComponent, and then introduce this component in the CreateComponent component, as follows:

import React from 'react'
import NewComponent from "./newComponent.js";

class CreateComponent extends React.Component {
  constructor () {
    super()
    console.log('construct:页面初始化');
    this.state = {
      content:'测试组件',
      isDelete:false
    }
  }

  componentWillMount () {
    console.log('componentWillMount:页面将要渲染')
  }

  componentDidMount () {
    console.log('componentDidMount:页面渲染结束')
  }

  deleteFunc = () => {
    this.setState({
      isDelete:true
    })
  }


    render() {
      console.log('render:页面渲染');
      return (
       <p>
         页面渲染
         <input type="button" value=&#39;删除&#39; onClick={this.deleteFunc}/>
         {!this.state.isDelete?(
          <NewComponent content={this.state.content}/>
         ):(null)}

      </p>


      )
    }

}

export default CreateComponent;
Copy after login

When the delete button is clicked At that time, the component NewComponent will be deleted, and the componentWillUnmount function will be executed before deletion

Output result:

construct:页面初始化
componentWillMount:页面将要渲染
render:页面渲染
componentDidMount:页面渲染结束
componentWillUnmount:将要从页面中删除
Copy after login

The above life cycles are the component life cycles we will commonly use, and the component life cycle There is also the life cycle of the update phase, but these are relatively rarely used. Here is a brief introduction:

shouldComponentUpdate(nextProps, nextState)

Use this method to control whether the component is updated. Rendering, if false is returned, it will not be re-rendered, as follows

import React from 'react'
import NewComponent from "./newComponent.js";

class CreateComponent extends React.Component {
  constructor () {
    super()
    console.log('construct:页面初始化');
    this.state = {
      content:'测试组件',
      isDelete:false
    }
  }

  componentWillMount () {
    console.log('componentWillMount:页面将要渲染')
  }

  componentDidMount () {
    console.log('componentDidMount:页面渲染结束')
  }

  shouldComponentUpdate(nextProps, nextState){
    if(nextState.isDelete){
      return false;
    }

  }

  deleteFunc = () => {
    this.setState({
      isDelete:true
    })
  }


    render() {
      console.log('render:页面渲染');
      return (
       <p>
         页面渲染
         <input type="button" value=&#39;删除&#39; onClick={this.deleteFunc}/>
         {!this.state.isDelete?(
          <NewComponent content={this.state.content}/>
         ):(null)}

      </p>


      )
    }

}

export default CreateComponent;
Copy after login

At this time, click the delete button and the page is not rendered. That is because the return value is set to false in shouldComponentUpdate. When the return value is false, The page cannot be re-rendered. The first parameter of this function represents the latest props, and the second parameter represents the latest state

componentWillReceiveProps(nextProps)

The component receives new props from the parent component Called before, the function parameter nextProps represents the received data

In the NewComponent component:

import React from 'react';

class NewComponent extends React.Component {
  componentWillUnmount() {
    console.log('componentWillUnmount:将要从页面中删除');
  }

  componentWillReceiveProps(nextProps){
    console.log(nextProps);
  }

  render() {
    return (
      <p>
         {this.props.content}
      </p>
    );
  }

}

export default NewComponent;
Copy after login

In the component CreateComponent:

import React from 'react'
import NewComponent from "./newComponent.js";

class CreateComponent extends React.Component {
  constructor () {
    super()
    console.log('construct:页面初始化');
    this.state = {
      content:'测试组件',
      isDelete:false
    }
  }

  componentWillMount () {
    console.log('componentWillMount:页面将要渲染')
  }

  componentDidMount () {
    console.log('componentDidMount:页面渲染结束')
  }

  changeFunc = () => {
    this.setState({
      content:'文字修改'
    })
  }


    render() {
      console.log('render:页面渲染');
      return (
       <p>
         页面渲染
         <input type="button" value=&#39;修改content&#39; onClick={this.changeFunc}/>
         {!this.state.isDelete?(
          <NewComponent content={this.state.content}/>
         ):(null)}

      </p>


      )
    }

}

export default CreateComponent;
Copy after login

However, componentWillReceiveProps will start in react16.3.0 Deprecated later

componentWillUpdate:

This method is called before the component is re-rendered and will be deprecated after react16.3.0

componentDidUpdate :

The component re-renders and changes the changes to the real DOM and then calls

Note: The three life cycles of componentWillUpdate, componentWillReceiveProps, and componentWillMount will be in react116 .Begin to be deprecated after 3.0

Related recommendations:

React component life cycle instance analysis

##React component Dragact 0.1.4 detailed explanation

The above is the detailed content of Getting started with React: How to create components in React. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!