建立元件

這是基本示例的擴充套件:

基本結構

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.