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 class to the function or use arrow functions.
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);
}
}
Method 2 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.testVarible= "this is a test";
}
onMove = () => {
console.log(this.testVarible);
}
}
Method 2 is my preferred way but you are free to choose your own.
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);
}
}
Note If you want to update the view as well, you should use state
and setState
method when you set or change the value.
Example:
class MyContainer extends Component {
state = { testVarible: "this is a test" };
onMove = () => {
console.log(this.state.testVarible);
this.setState({ testVarible: "new value" });
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…