P
P
pcdesign2019-06-10 14:04:25
React Native
pcdesign, 2019-06-10 14:04:25

How to pass state to navigation?

Image:
5cfe38823fd52420330071.png
Snack:
https://snack.expo.io/@aimodding/clock2head
In the AppbarExample.js file, I declared state: How to pass this state to the header instead of subtitle?
state = { str: 'hello' };

Here is the code
/* @flow */

import * as React from 'react';
import { View, Platform, StyleSheet } from 'react-native';
import {
  Colors,
  Appbar,
  Paragraph,
  withTheme,
} from 'react-native-paper';
import type { Theme } from 'react-native-paper/types';

type Props = {
  navigation: any,
  theme: Theme,
};

const initialParams = {
  showLeftIcon: true,
  showSubtitle: true,
  showSearchIcon: true,
  showMoreIcon: true,
};

const MORE_ICON = Platform.OS === 'ios' ? 'more-horiz' : 'more-vert';

class AppbarExample extends React.Component<Props> {

  static navigationOptions = ({ navigation }) => {
    const params = { ...initialParams, ...navigation.state.params };

    return {
      header: (
        <Appbar.Header>
          {params.showLeftIcon && (
            <Appbar.BackAction onPress={() => navigation.goBack()} />
          )}
          <Appbar.Content
            title="Title"
            subtitle={params.showSubtitle ? 'subtitle' : null}
          />
          {params.showSearchIcon && (
            <Appbar.Action icon="search" onPress={() => {}} />
          )}
          {params.showMoreIcon && (
            <Appbar.Action icon={MORE_ICON} onPress={() => {}} />
          )}
        </Appbar.Header>
      ),
    };
  };

  state = { str: 'hello' };

  render() {
    const {
      navigation,
      theme: {
        colors: { background },
      },
    } = this.props;
    const params = { ...initialParams, ...navigation.state.params };


    return (
      <View
        style={[
          styles.container,
          {
            backgroundColor: background,
          },
        ]}>
        <Paragraph>{this.state.str}</Paragraph>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
    paddingVertical: 8,
  },
});

export default withTheme(AppbarExample);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Dunkin, 2019-06-16
@pcdesign

In the constructor, you can apply something like such a thing

this.props.navigation.setParams({
     makeSaveRequestCallback: this.makeSaveRequest.bind(this)
 });

And in a static method, this gap can be accessed like this, navigation.state.makeSaveRequestCallback();
It also works with ordinary parameters

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question