React 类组件简略语法

常规标准语法


class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
    };
    this.onIncrement = this.onIncrement.bind(this);
    this.onDecrement = this.onDecrement.bind(this);
  }
  onIncrement() {
    this.setState(state => ({ counter: state.counter + 1 }));
  }
  onDecrement() {
    this.setState(state => ({ counter: state.counter - 1 }));
  }
  render() {
    return (
      <div>
        <p>{this.state.counter}</p>
        <button
          onClick={this.onIncrement}
          type="button"
        >
          Increment
        </button>
        <button
          onClick={this.onDecrement}
          type="button"
        >
          Decrement
        </button>
      </div>
    );
  }
}

简略语法


  • Arrow Function 实现 auto-bind
  • 类属性( class properties ) 简化构造函数。
class Counter extends Component {
  state = {
    counter: 0,
  };
  onIncrement = () => {
    this.setState(state => ({ counter: state.counter + 1 }));
  }
  onDecrement = () => {
    this.setState(state => ({ counter: state.counter - 1 }));
  }
  render() {
    return (
      <div>
        <p>{this.state.counter}</p>
        <button
          onClick={this.onIncrement}
          type="button"
        >
          Increment
        </button>
        <button
          onClick={this.onDecrement}
          type="button"
        >
          Decrement
        </button>
      </div>
    );
  }
}

类属性尚在提案阶段,需要引入专门的babel插件处理。