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

发布时间:2019-08-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了react 代码优化(一) ——事件处理脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

React事件处理

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

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

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

3、阻止默认行为preventDefault

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

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

4、事件绑定

1、在构造函数中使用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,代码量多一点
2、使用属性初始化器语法绑定this(实验性)
class Introduce extends React.Component {
    handleClick = () => {
        console.log('hello')
    }
    render() {
        return (
            <div onClick={this.handleClick}>click me!</div>
        )
    }
}
这种属性初始化语法,将方法初始化为箭头函数,因此在创建函数的时候就绑定了this,无需再次绑定,这种需要结合babel转义,很方便
3、在调用的时候使用bind绑定this
class Introduce extends React.Component {
    handleClick() {
        console.log('hello')
    }
    render() {
        return (
            <div onClick={this.handleClick.bind(this)}>click me!</div>
        )
    }
}
4、在调用的时候使用箭头函数绑定this
class Introduce extends React.Component {
    handleClick() {
        console.log('hello')
    }
    render() {
        return (
            <div onClick={() => this.handleClick()}>click me!</div>
        )
    }
}
34这种方式会有性能影响并且如果回调函数作为属性传给子组件的时候会导致重新渲染的问题 
综上,方式一是官方推荐的,方式二是我们用起来比较好用的 也结合了 方式134的优点


脚本宝典总结

以上是脚本宝典为你收集整理的react 代码优化(一) ——事件处理全部内容,希望文章能够帮你解决react 代码优化(一) ——事件处理所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。