react 代码优化(一) ——事件处理

React的事件处理

一、React 的事件绑定属性的命名要采用驼峰时写法, 不能小写

二、要传入一个函数做为事件处理函数,不能是字符串

例如:<button onclick={handleMe}>click me!</button>

三、阻止默认行为preventDefault

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();  //阻止默认行为
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

四、事件绑定

一、在构造函数中使用bind绑定this
class Introduce extends React.Component {
    constructor (props) {
        super(props);
        this.handleClick = this.handleClick.bind(this)
    }
    
    handleClick() {
        console.log('hello')
    }
    
    render() {
        return (
            <div onClick={this.handleClick}>click me!</div>
        )
    }
}

优势:这种绑定方式 是官方推荐的,在类构造函数中绑定this, 只会生成一个方法实例, 而且绑定一次以后若是屡次用到这个方法,也不须要再绑定
缺点:即便不用到state,也须要添加类构造函数来绑定this,代码量多一点
二、使用属性初始化器语法绑定this(实验性)
class Introduce extends React.Component {
    handleClick = () => {
        console.log('hello')
    }
    render() {
        return (
            <div onClick={this.handleClick}>click me!</div>
        )
    }
}
这种属性初始化语法,将方法初始化为箭头函数,所以在建立函数的时候就绑定了this,无需再次绑定,这种须要结合babel转义,很方便
三、在调用的时候使用bind绑定this
class Introduce extends React.Component {
    handleClick() {
        console.log('hello')
    }
    render() {
        return (
            <div onClick={this.handleClick.bind(this)}>click me!</div>
        )
    }
}
四、在调用的时候使用箭头函数绑定this
class Introduce extends React.Component {
    handleClick() {
        console.log('hello')
    }
    render() {
        return (
            <div onClick={() => this.handleClick()}>click me!</div>
        )
    }
}
三、4这种方式会有性能影响而且若是回调函数做为属性传给子组件的时候会致使从新渲染的问题 
综上,方式一是官方推荐的,方式二是咱们用起来比较好用的 也结合了 方式一、三、4的优势
相关文章
相关标签/搜索