Reactjs 在React组件中使用箭头函数不会在父上下文(存在)上传输。这在arrow函数中仍然未定义
这是在render方法中定义的,但不是在调用arrow函数的eventHandler中定义的 我对npx create react应用程序projectName做了一个全新的记录,并重现了我在个人项目中遇到的一个意外问题Reactjs 在React组件中使用箭头函数不会在父上下文(存在)上传输。这在arrow函数中仍然未定义,reactjs,binding,arrow-functions,Reactjs,Binding,Arrow Functions,这是在render方法中定义的,但不是在调用arrow函数的eventHandler中定义的 我对npx create react应用程序projectName做了一个全新的记录,并重现了我在个人项目中遇到的一个意外问题 import React from 'react'; class RemoteSubmitButton extends React.Component { onSignUpClick = () => { debugger; // "this" is unde
import React from 'react';
class RemoteSubmitButton extends React.Component {
onSignUpClick = () => {
debugger; // "this" is undefined
};
render() {
debugger; // "this" is defined
return (
<button
type="button"
onClick={this.onSignUpClick}
>
Submit
</button>
);
}
}
export default RemoteSubmitButton;
每当我在arrow函数中引用它时,我都希望调用方法render方法的上下文能够继续。通过放置一些调试器,我发现这是在render方法中定义的,但不是在onSignUpClick方法中定义的。使用胖箭头函数传输代码时,无法保证知道哪个变量封装了作用域上下文。有效的解决方法是在类属性中使用手动绑定:
import React from 'react';
class RemoteSubmitButton extends React.Component {
constructor(props) {
super(props)
this.onSignUpClick = this.onSignUpClick.bind(this)
}
onSignUpClick() {
debugger; // "this" is defined
};
render() {
debugger; // "this" is defined
return (
<button
type="button"
onClick={this.onSignUpClick}
>
Submit
</button>
);
}
}
export default RemoteSubmitButton;
当调试器停止执行并出现引用错误时,您是否试图在控制台中访问此项,或者您正在使用console.logthis访问它?前者。后者似乎运作良好。这里的含义是上下文确实被继承了,但是在控制台中调试绑定的方法有问题吗?如何最好地调试这样的上下文?