在反应js中声明变量的位置 [英] Where to declare variable in react js

查看:88
本文介绍了在反应js中声明变量的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to declare a variable in a react-js class. The variable should be accessible in different functions. This is my code

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
    }
}

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

On onMove, the value of this.test is undefined. I Know that I could put the value on the state but I don't want to do it because each time the value changes, render() will be called which is not necessary. I am new to react, did I make something wrong?

推荐答案

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

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

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

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

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

For getting the context of class you have to bind the context of the function or use arrow functions.

方法1绑定context:

Method 1 to bind the context:

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是我的首选方式但你可以自由选择。

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

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

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

注意如果你想要要更新视图,在设置或更改值时应使用 state setState 方法。

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

示例:

class MyContainer extends Component {

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

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

这篇关于在反应js中声明变量的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆