详解三种方式在React中解决绑定this的作用域问题并传参
在React中时常会遇到this指向的作用域问题 从而导致undefined报错
先来个Demo:
功能很简单 点击按钮改变文字
import React from 'react'; export default class BindWithThis extends React.Component { constructor(props) { super(props); this.state = { msg:"BindWithThis" } } render() { return <div> <input type="button" value="Way1" onClick={this.changeMsg1}/> <hr/> <h3>{this.state.msg}</h3> </div> } changeMsg1(){ console.log(this) this.setState({ msg:"Way1" }) } }
但会遇到问题:Cannot read property ‘setState' of undefined
这是因为 在changeMsg1方法内部的this指向的并不是外面的组件 因而根本就不会有setState()方法了 自然会报错
为此 有三种解决方法
方式一:在事件处理函数中使用.bind()
只要这样即可:
render() { return <div> <input type="button" value="Way1" onClick={this.changeMsg1.bind(this)}/> <hr/> <h3>{this.state.msg}</h3> </div> }
bind()的作用是为前面的函数修改函数内部的this的指向 从而使得函数内部的this指向bind中的第一个参数
bind()还可以传值:
bind第一个参数后面的所有参数都会作为调用bind前面的函数的参数传递
render() { return <div> <input type="button" value="Way1" onClick={this.changeMsg1.bind(this,"壹","贰")}/> <hr/> <h3>{this.state.msg}</h3> </div> } changeMsg1(arg1,arg2){ this.setState({ msg:"Way1"+arg1+arg2 }) }
除了bind()之外 还有call()和apply() 它们都能改变函数内部的this的指向
不过bind()和call()/apply()的区别是:bind()并不会立即调用 而call()/apply()会立即调用
方式二:在构造函数中使用.bind()
当为一个函数调用bind 从而改变this的指向之后 bind函数的返回值是这个被改变this指向的函数的改变后的引用
bind并不会修改原函数的this的指向 而是返回一个修改后的函数的指向 因此需要重新接收方可生效
import React from 'react'; export default class BindWithThis extends React.Component { constructor(props) { super(props); this.state = { msg:"BindWithThis" } // 当为一个函数调用bind 改变this的指向之后 bind函数的返回值是这个被改变this指向的函数的改变后的引用 因此需要重新接收 this.changeMsg2 = this.changeMsg2.bind(this,"壹","贰") } render() { return <div> <input type="button" value="Way2" onClick={this.changeMsg2}/> <hr/> <h3>{this.state.msg}</h3> </div> } changeMsg2(arg1,arg2){ this.setState({ msg:"Way2"+arg1+arg2 }) } }
方式三:使用箭头函数
利用了箭头函数的特性:箭头函数内部的this永远指向调用者方的this
render() { return <div> <input type="button" value="Way3" onClick={() => {this.changeMsg3("壹","贰")}}/> <hr/> <h3>{this.state.msg}</h3> </div> } changeMsg3 = (arg1,arg2) => { this.setState({ msg:"Way3"+arg1+arg2 }) }
当然 更推荐使用更加方便的箭头函数
到此这篇关于详解三种方式在React中解决绑定this的作用域问题并传参的文章就介绍到这了,更多相关React绑定this作用域内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
React SSR架构Stream Rendering与Suspense for Data Fetching
这篇文章主要为大家介绍了React SSR架构Stream Rendering与Suspense for Data Fetching解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-03-03简析React Native startReactApplication 方法
这篇文章主要介绍了React Native startReactApplication 方法简析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-09-09JavaScript中的useRef 和 useState介绍
这篇文章主要给大家分享的是 JavaScript中的useRef 和 useState介绍,下列文章,我们将学习 useRef 和 useState hook是什么,它们的区别以及何时使用哪个。 这篇文章中的代码示例将仅涉及功能组件,但是大多数差异和用途涵盖了类和功能组件,需要的朋友可以参考一下2021-11-11react axios配置代理(proxy),如何解决本地开发时的跨域问题
这篇文章主要介绍了react axios配置代理(proxy),如何解决本地开发时的跨域问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-07-07
最新评论