Home  >  Article  >  Web Front-end  >  There are several ways to declare react components

There are several ways to declare react components

青灯夜游
青灯夜游Original
2021-11-25 15:34:482711browse

There are three ways to declare react components: 1. Use functional methods to define stateless components; 2. Use the "React.createClass()" method to define components; 3. Use "React.Component()" Methods define components in ES6 style.

There are several ways to declare react components

The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.

The way react declares (creates) components:

After the launch of React, there have been three methods of defining react components for different reasons. Methods, different approaches lead to the same goal;

Three specific ways:

  • Functional definition of stateless components

  • React.createClass( ) Define components

  • React.Component() Define components

Although there are three ways to define react components, then these three ways to define components What's the difference? In other words, why do corresponding definitions appear? Let’s briefly introduce it below.

Stateless functional components

The creation of stateless functional components has appeared since 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 built into other components through simple combination; this A design pattern is advocated in which multiple simple applications are combined into one large application.

The stateless functional component is formally represented as a component class with only one render method. It 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)

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 have the following significant features:

The creation form of stateless components makes the code more readable and reduces a lot of redundant code. Simplified to only one render method, which greatly enhances the convenience of writing a component. In addition, stateless components have the following notable features:

  • The component will not be instantiated ization, 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 instantiated in the process of component instantiation. There is no instance. There is no need to allocate excess memory during the optimization process, thereby improving performance to a certain extent.

  • 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 to be written as simply as possible in large projects to split 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, Use stateless components whenever possible.

React.createClass

React.createClass is the first recommended way to create components in react. This is a React component implemented in ES5's native JavaScript. Its form 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;
};

Compared with stateless components, React.createClass and React.Component to be described later create stateful components. These components are to be instantiated and can access the life of the component. cycle method. 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 the things you need to care about) function) results in unnecessary performance overhead and increases the likelihood of code becoming obsolete.

  • The mixins of React.createClass are 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".

React.Component

React.Component是以ES6的形式来创建react的组件的,是React目前极为推荐的创建有状态组件的方式,最终会取代React.createClass形式;相对于 React.createClass可以更好实现代码复用。将上面React.createClass的形式改为React.Component形式如下:

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;
};

推荐学习:《react视频教程

The above is the detailed content of There are several ways to declare react components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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