在反应js

时间:2017-11-21 15:52:54

标签: javascript reactjs

我试图在react-js类中声明一个变量。变量应该可以在不同的函数中访问。这是我的代码

class MyContainer extends Component {
    constructor(props) {
        super(props);
        this.testVarible= "this is a test";  // I declare the variable here
    }
    onMove() {
        console.log(this.testVarible); //I try to access it here
    }
}

在onMove上,this.test的值未定义。我知道我可以将值放在状态上,但我不想这样做,因为每次值改变时,都会调用render(),这是不必要的。我是新手做出反应,我做错了吗?

2 个答案:

答案 0 :(得分:31)

在React中使用ES6语法不会将this绑定到用户定义的函数,但它会将this绑定到组件生命周期方法。

因此,您声明的函数与该类没有相同的上下文,并且尝试访问this将无法满足您的期望。

要获取类的上下文,必须绑定函数的上下文或使用箭头函数。

绑定上下文的方法1:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

方法2绑定上下文:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

方法2是我首选的方式,但您可以自由选择。

更新:您还可以在没有构造函数的情况下在类上创建属性:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

注意如果您还要更新视图,则应在设置或更改值时使用statesetState方法。

示例:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

答案 1 :(得分:4)

假设onMove是一个事件处理程序,它的上下文可能不是MyContainer的实例,即this指向不同的东西。

您可以在构建实例期间通过Function.bind

手动绑定函数的上下文
class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

此外, test !== testVariable

相关问题