[英]Accessing component variables from methods
在我的应用程序中,我有一个组件,其构造函数中有一个状态变量和一个组件变量。 但是,如果我尝试通过调整窗口大小来从我的方法访问它们,则会得到undefined
并且cannot read property 'test' of undefined
undefined
cannot read property 'test' of undefined
。
import React from 'react';
class Testapp extends React.Component {
constructor(props) {
super(props);
this.state = {test: "he"};
this.test = "hu";
window.addEventListener('resize', this.testCallback);
}
testCallback() {
console.log(this.test);
console.log(this.state.test);
}
render() {
return( <p>Hello world</p> );
}
}
export default Testapp;
如何从方法访问这些属性?
您的函数无法在正确的上下文中访问this
变量。
最简单的解决方案是转换为箭头函数
testCallback = () => {
console.log(this.test);
console.log(this.state.test);
}
这将为您的函数提供this
的正确上下文。
或者,您可以在构造函数中手动bind
它。
constructor(props) {
super(props);
this.state = {test: "he"};
this.test = "hu";
window.addEventListener('resize', this.testCallback);
this.testCallback = this.testCallback.bind(this);
}
只需使用箭头函数即可。 或者,您可以将“this”绑定到方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.