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;