在反应js中声明变量的位置

use*_*567 30 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Bri*_*kta 54

在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

方法2绑定上下文:

class MyContainer extends Component {

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

    onMove = () => {
        console.log(this.testVarible);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

例:

class MyContainer extends Component {

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

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*imo 6

假设这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);
  }
}
Run Code Online (Sandbox Code Playgroud)

另外,test !== testVariable