创建组件

这是基本示例的扩展:

基本结构

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 返回。无状态功能组件更具可重用性,并对你的应用程序产生积极的性能影响。

它们有两个主要特征:

  1. 渲染时,它们会收到一个带有传递下来的所有道具的对象
  2. 他们必须返回要渲染的 JSX
// When using JSX inside a module you must import React
import React from 'react';
import PropTypes from 'prop-types';

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

//arrow components also may have props validation
FirstComponent.propTypes = {
    name: PropTypes.string.isRequired,
}

// To use FirstComponent in another file it must be exposed through an export call:
export default FirstComponent;

有状态组件

In contrast to the ‘stateless’ components shown above, ‘stateful’ components have a state object that can be updated with the setState method. The state must be initialized in the constructor before it can be set:

import React, { Component } from 'react';

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

        this.state = {
            toggle: true
        };

        // This is to bind context when passing onClick as a callback
        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>
        );
    }
}

Extending a component with PureComponent instead of Component will automatically implement the shouldComponentUpdate() lifecycle method with shallow prop and state comparison. This keeps your application more performant by reducing the amount of un-necessary renders that occur. This assumes your components are ‘Pure’ and always render the same output with the same state and props input.

Higher Order Components

Higher order components (HOC) allow to share component functionality.

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

Higher order components are used when you want to share logic across several components regardless of how different they render.