React Doc 简单摘要 (三)

来源:互联网 发布:最优化计算方法黄正海 编辑:程序博客网 时间:2024/06/05 04:48

事件处理

注意命名规范:

  • 驼峰命名:原来的 onclick 变成 onClick
  • 处理函数: handle*

注意 this 指针的绑定。

class Toggle extends React.Component {    constructor(props) {        super(props);        this.state = {isToggleOn: true};        // This binding is necessary to make 'this' work in the callback        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>        );    }}ReactDOM.render(    <Toggle />,    document.getElementById('root'));
原创粉丝点击