React事件绑定的方式有哪些-创新互联
今天小编给大家分享一下React事件绑定的方式有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
一、是什么
在react
应用中,事件名都是用小驼峰格式进行书写,例如onclick
要改写成onClick
最简单的事件绑定如下:
class ShowAlert extends React.Component { showAlert() { console.log("Hi"); } render() { return
从上面可以看到,事件绑定的方法需要使用{}
包住
上述的代码看似没有问题,但是当将处理函数输出代码换成console.log(this)
的时候,点击按钮,则会发现控制台输出undefined
二、如何绑定
为了解决上面正确输出this
的问题,常见的绑定方式有如下:
render方法中使用bind
render方法中使用箭头函数
constructor中bind
定义阶段使用箭头函数绑定
render方法中使用bind
如果使用一个类组件,在其中给某个组件/元素一个onClick
属性,它现在并会自定绑定其this
到当前组件,解决这个问题的方法是在事件函数后使用.bind(this)
将this
绑定到当前组件中
class App extends React.Component { handleClick() { console.log("this > ", this); } render() { return (test
这种方式在组件每次render
渲染的时候,都会重新进行bind
的操作,影响性能
render方法中使用箭头函数
通过ES6
的上下文来将this
的指向绑定给当前组件,同样在每一次render
的时候都会生成新的方法,影响性能
class App extends React.Component { handleClick() { console.log("this > ", this); } render() { return (this.handleClick(e)}>test
constructor中bind
在constructor
中预先bind
当前组件,可以避免在render
操作中重复绑定
class App extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log("this > ", this); } render() { return (test
定义阶段使用箭头函数绑定
跟上述方式三一样,能够避免在render
操作中重复绑定,实现也非常的简单,如下:
class App extends React.Component { constructor(props) { super(props); } handleClick = () => { console.log("this > ", this); } render() { return (test