事件处理

react元素的时间处理和DOM的很相似,只是语法上面有一点区别

区别:

  1.react属性命名为小驼峰  && 如果使用jsx语法,需要传入的是一个函数,而不是字符串(eg:onClick={click})

  2.react阻止默认事件不能是return false了,必须使用preventDefault

  3.this的指向问题:

    类的方法默认是不会绑定this的,所以如果不进行this的绑定,那么this会是undefined。解决方案:

      1.使用bind进行this的绑定

        constructor(props){
          super(props);
          this.state = ({open:true})
          this.clickTest  = this.clickTest.bind(this)
        }
        clickTest(){
          this.setState(prevState=>({
            open:!prevState.open
          }))
        }
        render() {
          return (
            <div onClick={this.clickTest}>{{this.state.open}}</div>
          )
        }
      2.调用的地方换个方式去调
        constructor(props){
          super(props);
          this.state = ({open:true})
        }
        clickTest(){
          this.setState(prevState=>({
            open:!prevState.open
          }))
        }
        render() {
          return (
            <div onClick={(e) => this.clickTest(e)}>{{this.state.open}}</div>
          )
        }
      3.使用属性初始化器语法
        clickTest =()=>(){
          console,log(this)
        }
        render() {
          return (
            <div onClick={this.clickTest}>{{this.state.open}}</div>
          )
        }
    4.传参: 
      <div onClick={this.clickTest.bind(this,id)}>{{this.state.open}}</div>  // 事件对象e是在参数后面
      <div onClick={(e=> this.clickTest(id,e)}>{{this.state.open}}</div>
posted @ 2019-09-03 17:23  前端小可爱  阅读(157)  评论(0编辑  收藏  举报