Reputation: 3176
How to solve this? I have a custom Button component that gets included in my ModalScreen. It all seems to work but the onPress function is acting up. It seems to have lost the scope for some reason so I can't reference this
or even add params to the function. What am I missing here?
import React from 'react';
import {
Text,
View,
} from 'react-native';
import Styles from 'app/constants/Styles';
import Button from 'app/components/Button';
export default class ModalScreen extends React.Component {
onBtnPress() {
console.log('dfsdfsdf'); /// << this gets consoled out just fine
//this.props.navigation.navigate('Main'); <<<< this won't work
}
render() {
return (
<View style={Styles.center}>
<Text>MOdalScreen</Text>
<Button label='Gå vidare' onPress={ this.onBtnPress }/>
</View>
);
}
}
Button.js
import React, { Component } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import Styles from 'app/constants/Styles'
import Vars from 'app/constants/Vars'
export default class Button extends Component {
render() {
return (
<TouchableOpacity style={[Styles.round, Styles.primaryBackground]} onPress={this.props.onPress}>
<Text style={[Styles.label, Styles.textCenter, { margin: Vars.spacing.narrow }]}>
{this.props.label}
</Text>
</TouchableOpacity>
)
}
}
Upvotes: 0
Views: 4600
Reputation: 641
You're right that it's lost the scope. You just need to bind the scope to the handle function somehow before you give it to the Button component. One popular way is with a handy arrow function:
<Button label='Gå vidare' onPress={ () => this.onBtnPress() }/>
Or you could use bind in the constuctor:
export default class ModalScreen extends React.Component {
constructor(props) {
super(props);
this.onBtnPress = this.onBtnPress.bind(this)
}
onBtnPress() {
console.log('dfsdfsdf'); /// << this gets consoled out just fine
//this.props.navigation.navigate('Main'); <<<< this won't work
}
Upvotes: 2