Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  158] [ 5]  / answers: 1 / hits: 25678  / 7 Years ago, tue, march 28, 2017, 12:00:00

I am a complete newbie in react native, react.js, and javascript. I am Android developer so would like to give RN a try.



Basically, the difference is in onPress;



This code shows 'undefined' when toggle() runs:



class LoaderBtn extends Component {
constructor(props) {
super(props);
this.state = { loading: false };
}

toggle() {
console.log(this.state);
// let state = this.state.loading;
console.log(Clicked!)
// this.setState({ loading: !state })
}

render() {
return (
<Button style={{ backgroundColor: '#468938' }} onPress={this.toggle}>
<Text>{this.props.text}</Text>
</Button>
);
}
}


but this code works:



class LoaderBtn extends Component {
constructor(props) {
super(props);
this.state = { loading: false };
}

toggle() {
console.log(this.state);
// let state = this.state.loading;
console.log(Clicked!)
// this.setState({ loading: !state })
}

render() {
return (
<Button style={{ backgroundColor: '#468938' }} onPress={() => {this.toggle()}}>
<Text>{this.props.text}</Text>
</Button>
);
}
}


Can you explain me the difference, please?



In Java / Kotlin we have method references, basically it passes the function if signatures are the same, like onPress = () => {} and toggle = () => {}



But in JS it doesn't work :(


More From » reactjs

 Answers
344

The issue is that in the first example toggle() is not bound to the correct this.


You can either bind it in the constructor:


constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
...


Or use an instance function (OK under some circumstances):


toggle = () => {
...
}

This approach requires build changes via stage-2 or transform-class-properties.


The caveat with instance property functions is that there's a function created per-component. This is okay if there aren't many of them on the page, but it's something to keep in mind. Some mocking libraries also don't deal with arrow functions particularly well (i.e., arrow functions aren't on the prototype, but on the instance).


This is basic JS; this article regarding React Binding Patterns may help.


[#58350] Sunday, March 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eddiejoshb

Total Points: 659
Total Questions: 105
Total Answers: 100

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;