繁体   English   中英

从方法访问组件变量

[英]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.

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