用ts重写React官方文档里的demo(3)——事件处理2

52 阅读1分钟
import React from 'react';

interface Props {

}

interface State {
    isToggleOn: boolean;
}

class Toggle extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {isToggleOn: true}

        // 为了在回调中使用 ‘this’,这个绑定是必不可少的
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState(prevState => ({
            isToggleOn: !prevState.isToggleOn 
        }));
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                {this.state.isToggleOn ? 'ON' : 'OFF'}
            </button>
        )
    }
}

export default Toggle;