I have following code where onPress im expecting to call a function.
class BarButton extends Component { render() { const {imageUri,onPress} = this.props; return ( <TouchableOpacity style={styles.buttonStyle} onPress={() => onPress()} > <Image source={imageUri} style = {styles.buttonStyle}/> </TouchableOpacity> ); } } BarButton.propTypes = { onPress: PropTypes.func.isRequired, imageUri:PropTypes.string.isRequired }; export default class ShopScreen extends Component { static navigationOptions = { title: 'Shop', headerRight: <BarButton imageUri={require('./images/filter.png')} onPress={ this.onPressButton}/>, headerTintColor:'black' }; constructor(props){ super(props); this.state ={ isLoading: true} this.onPressButton = this.onPressButton.bind(this); } onPressButton() { this.props.navigation.navigate('Filter'); }
So I want to call the function onPressButton and navigate to next screen , in this I get error
You can use the navigation
object that navigationOptions
receive when you use a function instead of an object.
static navigationOptions = ({ navigation }) => {
return {
title: 'Shop',
headerRight: (
<BarButton
imageUri={require('./images/filter.png')}
onPress={() => navigation.navigate('Filter')}
/>
),
headerTintColor:'black'
};
};
Basically as a newbie i failed to understand that navigationOptions is a static var so can't reference anything using "this", following thread proposes many solutions here is the original link and out of all the on worked for me is as follows, posting it here for ease (with due credit to original author https://github.com/jacse )
https://github.com/react-navigation/react-navigation/issues/145
class MyScreen extends React.Component { static navigationOptions = ({ navigation }) => { const { params = {} } = navigation.state; return { headerRight: <Button title="Save" onPress={() => params.handleSave()} /> }; }; _saveDetails = () => { console.log('clicked save'); console.log('clicked save ' + this.state.xxxxxx); } componentDidMount() { this.props.navigation.setParams({ handleSave: this._saveDetails }); } render() { return ( <View /> ); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.