反应导航 goBack() 并设置父状态

时间:2021-02-21 19:12:09

标签: reactjs react-native

我有一个页面。画面如下

import React, { useState } from "react";
import { Button, Text, View } from "react-native";
export default function ViewA() {
     const [val, setVal] = useState('')
     return (
          <View>
               <Text>{val}</Text>
               <Button title="Next" onPress={()=>navigation.navigate(?)} />
          </View>
     );
}

和另一个页面。画面如下:

import React from "react";
import { Button } from "react-native";
export default function ViewB() {
     return <Button title="back" onPress={()=>navigation.goBack(?) } />;
}

我有两个 Screen viewA 和 viewB。在viewA 中有一个按钮。当按钮按下时导航到 viewB 并将 setVal() 函数作为参数传递。然后在屏幕视图B中,当返回按钮点击setVal()调用新值和navigation.goBack()调用返回到视图A

1 个答案:

答案 0 :(得分:1)

您必须将回调函数作为参数从屏幕 A 传递到 B,当屏幕 B 中的按钮按下时,传递您想在屏幕 A 中设置的新值。

完整代码:

屏幕 A

import React, { useState } from "react";
import { Text, View, Button } from "react-native";

const ViewA = ({ navigation }) => {
  const [val, setVal] = useState(null);

  const callBack = (value) => {
    setVal(value);
  };

  const onNextPress = () => {
    navigation.navigate("Second Screen", { callBack: callBack });
  };

  return (
    <View>
      <Text>{val}</Text>
      <Button title="Next" onPress={onNextPress} />
    </View>
  );
};

export default ViewA;

屏幕 B

import React from "react";
import { View, Button } from "react-native";

const ViewB = ({ route, navigation }) => {
  const onBackPress = () => {
    const { callBack } = route.params;
    callBack(5); // Your new value to set
    navigation.goBack();
  };

  return (
    <View>
      <Button title="back" onPress={onBackPress} />
    </View>
  );
};

export default ViewB;

希望能帮到你!