zoukankan      html  css  js  c++  java
  • 事件处理

    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>
  • 相关阅读:
    09.回文数
    08.字符串转换位整数
    背景图片自适应
    认证 (authentication) 和授权 (authorization) 的区别
    vue-组件之间传值
    数组对象去重
    二进制数转换十进制数
    node-删除对象中指定属性失效问题-JSON.parse实例化
    Vue-动态修改数组
    正则遇到的问题集合
  • 原文地址:https://www.cnblogs.com/liyaping/p/11454302.html
Copyright © 2011-2022 走看看