How to send data back to previous sceen when using navigation.goBack()?

前端 未结 3 1401
春和景丽
春和景丽 2021-01-04 22:29

I\'ve got screen 1 from which I navigate to screen 2 using:

navigation.navigate(\'Screen2\')

From this screen, I would like to go to the pr

相关标签:
3条回答
  • 2021-01-04 23:05

    You can pass a callback (onSelect) like this:

    // SCREEN 1
    import React from "react";
    import { Button, Text, View } from "react-native";
    
    class Screen1 extends React.Component {
      state = { selected: false };
    
      onSelect = data => {
        this.setState(data);
      };
    
      onPress = () => {
        this.props.navigate("Screen2", { onSelect: this.onSelect });
      };
    
      render() {
        return (
          <View>
            <Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
            <Button title="Next" onPress={this.onPress} />
          </View>
        );
      }
    }
    
    // SCREEN 2
    import React from "react";
    import { Button } from "react-native";
    
    class Screen2 extends React.Component {
      goBack() {
        const { navigation } = this.props;
        navigation.goBack();
        navigation.state.params.onSelect({ selected: true });
      }
    
      render() {
        return <Button title="back" onPress={this.goBack} />;
      }
    }
    
    0 讨论(0)
  • 2021-01-04 23:07

    You can solve it with 2 ways :

    1 : Using navigation method

    Pass a method when you are calling that screen through navigation :

    this.props.navigation.navigate('Screen2', {
      onGoBack: this.refresh,
    });
    
    refresh=(data)=> {
    
    }
    

    and when you press back, pass data like

    this.props.navigation.state.params.onGoBack('123');
    this.props.navigation.goBack();
    

    2 : Using redux store

    If you are using redux in your application, just update redux store whenever user presses back button, and get store value in previous screen.

    0 讨论(0)
  • 2021-01-04 23:22

    if you're using v2 or newer, another possibility is using the navigate function, providing key / routeName of the route you're going back to and the params. docs: https://reactnavigation.org/docs/en/navigation-actions.html#navigate

    0 讨论(0)
提交回复
热议问题