React 创建组件

示例

这是基本示例的扩展:

基本结构

import React, { Component } from 'react';
import { render } from 'react-dom';

class FirstComponent extends Component {
    render() {
        return (
            <div>
                Hello, {this.props.name}! I am a FirstComponent.
            </div>
        );
    }
}

render(
    <FirstComponent name={ 'User' } />,
    document.getElementById('content')
);

上面的示例称为无状态组件,因为它不包含状态(按词的React含义)。

在这种情况下,某些人会发现最好使用基于ES6箭头功能的无状态功能组件。

无状态功能组件

在许多应用程序中,有一些智能组件可以保持状态,但可以渲染笨拙的组件,这些组件仅接收道具并将HTML作为JSX返回。无状态功能组件具有更高的可重用性,并对您的应用程序产生积极的性能影响。

它们具有2个主要特征:

  1. 渲染时,他们会收到一个带有所有传递下来的道具的对象

  2. 他们必须返回要渲染的JSX

// 在模块内部使用JSX时,必须导入React
import React from 'react';
import PropTypes from 'prop-types';

const FirstComponent = props => (
    <div>
        Hello, {props.name}! I am a FirstComponent.
    </div>
);

//箭头组件也可能具有道具验证
FirstComponent.propTypes = {
    name: PropTypes.string.isRequired,
}

// 要在另一个文件中使用FirstComponent,必须通过导出调用将其公开:
export default FirstComponent;

状态组件

与上面显示的“无状态”组件相反,“有状态”组件具有可以用该setState方法更新的状态对象。必须先在中初始化状态,constructor然后才能设置状态:

import React, { Component } from 'react';

class SecondComponent extends Component {
    constructor(props) {
        super(props);

       this.state= {
            toggle: true
        };

        // 这是在传递onClick作为回调时绑定上下文
       this.onClick= this.onClick.bind(this);
    }

    onClick() {
        this.setState((prevState, props) => ({
            toggle: !prevState.toggle
        }));
    }
    
    render() {
        return (
            <div onClick={this.onClick}>
                Hello, {this.props.name}! I am a SecondComponent.
                <br />
                Toggle is: {this.state.toggle}
            </div>
        );
    }
}

用PureComponent代替扩展组件Component将自动实现shouldComponentUpdate()具有浅支持和状态比较的生命周期方法。这样可以减少不必要的渲染次数,从而使应用程序的性能更高。这假设您的组件是“纯”的,并且始终以相同的状态和道具输入呈现相同的输出。

高阶组件

高阶组件(HOC)允许共享组件功能。

import React, { Component } from 'react';

const PrintHello = ComposedComponent => class extends Component {
    onClick() {
        console.log('hello');
    }
    
    /* The higher order component takes another component as a parameter 
    and then renders it with additional props */
    render() {
        return <ComposedComponent {...this.props } onClick={this.onClick} />
    }
}

const FirstComponent = props => (
    <div onClick={props.onClick}>
        Hello, {props.name}! I am a FirstComponent.
    </div>
);

const ExtendedComponent = PrintHello(FirstComponent);

当您想要在多个组件之间共享逻辑时,无论它们呈现的差异如何,都使用高阶组件。