简体   繁体   English

React在没有箭头函数的回调中访问setState

[英]React accessing setState in callback without arrow function

I am developing code for the corporate intranet.我正在为企业内部网开发代码。 Once the base was built using arrow functions I tested in Internet Exploder.使用箭头函数构建基础后,我在 Internet Exploder 中进行了测试。 Discovering that it will not accept arrow functions.发现它不会接受箭头函数。 I am using React for this project and have since refactored all the code to use classic function calls.我在这个项目中使用 React,并且已经重构了所有代码以使用经典函数调用。

It mostly works except for one minor glitch: I cannot access this from inside the function call.除了一个小故障外,它主要工作:我无法从函数调用内部访问它。

Here is one example of code, although there are others:这是一个代码示例,尽管还有其他示例:

<NavLink onClick={function () { 
    this.setState({ openCount: item.pageId }); 
    this.props.CurrentPage_Update(item) 
    }
} 
className="menu menu-link" 
key={"DDNavLink_" + item.pageId}>
{item.title}
</NavLink>

How can I access the 'this' object for all my function calls?如何访问所有函数调用的“this”对象? I tried creating a variable in the order of var set=this.setState;我尝试按照var set=this.setState;的顺序创建一个变量var set=this.setState; but that failed, although it does work with bound functions.但这失败了,尽管它确实适用于绑定函数。

I am not sure where to go although I have read about babel but am completely agnostic about it's use and function, especially for such a seemingly simple refactor.虽然我读过 babel,但我不知道该去哪里,但我完全不知道它的用途和功能,尤其是对于这样一个看似简单的重构。

Thanks谢谢

At the end of every function call I used .bind(this) to enable the function to use the external this rather than the internal.在每个函数调用结束时,我使用 .bind(this) 使函数能够使用外部 this 而不是内部。

//blah blah blah
}.bind(this)

I found that I have to do it at the end of every closing brace if there are any calls to this within the function.我发现如果函数中有任何对 this 的调用,我必须在每个右大括号的末尾执行此操作。 I plan on making it a habit for every classic function call whether it is necessary or not.无论是否有必要,我都计划让每个经典的函数调用都成为一种习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM