Home > Web Front-end > JS Tutorial > What are the several ways to declare react components?

What are the several ways to declare react components?

coldplay.xixi
Release: 2020-11-20 09:33:01
Original
2809 people have browsed it

Declaration method of react components: 1. Functionally defined stateless components; 2. Components defined in es5 native way [React.createClass]; 3. Components defined in es6 form [extends React.Component] .

What are the several ways to declare react components?

Declaration method of react component:

1. Stateless functional component

Creating stateless functional component forms began to appear in React version 0.14. It is used to create pure display components, which are only responsible for display based on the incoming props and do not involve state operations. Specific stateless functional components, the official pointed out:

In most React codes, most components are written as stateless components, which can be constructed into other components through simple combination;

This design pattern is advocated by combining multiple simple applications into one large application.

The stateless functional component is formally represented as a component class with only one render method, which is created in the form of a function or ES6 arrow function, and the component is stateless. The specific creation form is as follows:

function HelloComponent(props, /* context */) {
  return <div>Hello {props.name}</div>
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode)
Copy after login

The creation form of stateless components makes the code more readable, and reduces a lot of redundant code, simplifying it to only one render method, which greatly enhances the ability to write a In addition to the convenience of components, stateless components also have the following notable features:

  • The components will not be instantiated, and the overall rendering performance is improved

    Because the component is simplified into a function of the render method, since it is a stateless component, the stateless component will not be in the process of component instantiation, and the non-instantiation process does not need to allocate excess memory, thereby improving performance. get a certain improvement.

  • Components cannot access this object

    Stateless components have no instantiation process, so they cannot access objects in component this, such as: this.ref, this.state None can access it. If you want to access, you cannot use this form to create components

  • Components cannot access life cycle methods

    Because stateless components do not require component life cycle management and status Management, so the underlying implementation of this form of component will not implement the component's life cycle method. Therefore, stateless components cannot participate in the various life cycle management of components.

  • Stateless components can only access input props. The same props will get the same rendering results without side effects

    Stateless components are encouraged in large projects Try to use simple writing methods to divide the originally huge components. In the future, React will also perform a series of optimizations for stateless components, such as meaningless checks and memory allocation, so whenever possible, try to use stateless components.

<strong>2. React.createClass</strong>

React.createClass is the recommended way to create components in the beginning of react. This It is a React component implemented in ES5's native JavaScript. Its form is as follows:

var InputControlES5 = React.createClass({
    propTypes: {//定义传入props中的属性各种类型
        initialValue: React.PropTypes.string
    },
    defaultProps: { //组件默认的props对象
        initialValue: &#39;&#39;
    },
    // 设置 initial state
    getInitialState: function() {//组件相关的状态对象
        return {
            text: this.props.initialValue || &#39;placeholder&#39;
        };
    },
    handleChange: function(event) {
        this.setState({ //this represents react component instance
            text: event.target.value
        });
    },
    render: function() {
        return (
            <div>
                Type something:
                <input onChange={this.handleChange} value={this.state.text} />
            </div>
        );
    }
});
InputControlES6.propTypes = {
    initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
    initialValue: &#39;&#39;
};
Copy after login

Compared with stateless components, React.createClass and the React.Component to be described later are all created Stateful components are components that are instantiated and have access to the component's lifecycle methods. However, with the development of React, problems with the React.createClass form itself have been exposed:

React.createClass will self-bind function methods (unlike React.Component which only binds functions that need to be concerned), resulting in unnecessary Performance overhead, increasing the likelihood of code becoming obsolete.

React.createClass'smixins is not natural and intuitive enough; the React.Component form is very suitable for higher-order components (Higher Order Components--HOC), which displays the mixins in a more intuitive form More powerful functions, and HOC is pure JavaScript, no need to worry about them being abandoned. For HOC, please refer to "Stateless Components and Higher-Order Components".

<strong>3. React.Component</strong>

React.Component creates react components in the form of ES6, which is currently highly recommended by React The way of creating stateful components will eventually replace the React.createClass form; compared to React.createClass, code reuse can be better achieved. Change the form of React.createClass above to the form of React.Component as follows:

class InputControlES6 extends React.Component {
    constructor(props) {
        super(props);
        // 设置 initial state
        this.state = {
            text: props.initialValue || &#39;placeholder&#39;
        };
        // ES6 类中函数必须手动绑定
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({
            text: event.target.value
        });
    }
    render() {
        return (
            <div>
                Type something:
                <input onChange={this.handleChange}
               value={this.state.text} />
            </div>
        );
    }
}
InputControlES6.propTypes = {
    initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
    initialValue: &#39;&#39;
};
Copy after login

Related learning recommendations: javascript video tutorial

The above is the detailed content of What are the several ways to declare react components?. 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