美文网首页
学习笔记:React事件处理

学习笔记:React事件处理

作者: 双鱼子曰1987 | 来源:发表于2021-03-26 09:08 被阅读0次

    一、React 事件处理

    • React 元素的事件处理和 DOM 元素类似,但是有一点语法上的不同。
    // HTML 通常写法是:
    <button onclick="activateLasers()">
      激活按钮
    </button>
    
    //React 中写法为:
    <button onClick={activateLasers}>
      激活按钮
    </button>
    
    • React 事件绑定属性的命名采用驼峰式写法,而不是小写。
    • 如果采用 JSX 的语法,需要传入一个函数作为事件处理函数,即xxx = { 方法名 }
    • 在 React 中不能使用返回 false 的方式阻止方法的默认行为,必须明确使用 preventDefault
    class TapButton extends React.Component {
      constructor(props){
        super(props);
    
        this.state = {isToggleOn: true};
    
        // 为了在回调中使用 `this`,这个绑定是必不可少的
        this.clickHandler = this.clickHandler.bind(this);
      }
    
      render() {
        return <button onClick={this.clickHandler}> {this.state.isToggleOn ? "ON" : "OFF"} </button>
      }
    
      clickHandler() {
        this.setState(state => ({
          isToggleOn: !state.isToggleOn
        }));
      }
    }
    
    • JSX 回调函数中的 this,类的方法默认是不会绑定 this 的。未绑定的时候,当你调用这个函数的时候 this 的值会是 undefined

    相关文章

      网友评论

          本文标题:学习笔记:React事件处理

          本文链接:https://www.haomeiwen.com/subject/vddzqltx.html