React Native Stack Navigator传递道具

时间:2020-02-07 11:55:09

标签: react-navigation react-navigation-stack

我想将一些道具(值)传递到另一页,而我正在使用stackNavigator

App.js:

import Insert from "./components/pages/Insert";
import ViewData from "./components/pages/ViewData";

const Stack = createStackNavigator();

NavigationContainer>
        <Stack.Navigator headerMode={false}>
          <Stack.Screen name="Insert Your data" component={Insert} />
          <Stack.Screen name="ViewData" component={ViewData} />
        </Stack.Navigator>
      </NavigationContainer>

Insert.js

const Insert = ({ props, navigation: { navigate } }) => {
  const [enteredName, setEnteredName] = useState();
  const [enteredSurname, setEnteredSurname] = useState();

const sendValues = (enteredName, enteredSurname) => {
    setEnteredName(enteredName);
    setEnteredSurname(enteredSurname);
    navigate("ViewData", {
      name: enteredSurname,
      surname: enteredSurname
    });
  };

...

<View>
          <Button
            title="Submit"
            onPress={() => sendValues(enteredName, enteredSurname)}
          />

ViewData.js

const ViewData = ({props, navigation: { goBack } }) => {
  let name = enteredName;

  console.log(name); /// I always get undefined

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <Text>Here {name}</Text>
      <Button onPress={() => goBack()} title="Edit Data" />
    </View>
  );
};

提交时,控制台始终是未定义的。 当然,我在某个地方误了。

有什么主意吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

请参阅https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props

为屏幕使用渲染回调,而不是指定组件 道具:

<Stack.Screen name="Home">
  {props => <HomeScreen {...props} extraData={someData} />}
</Stack.Screen>

您可以这样更改

import Insert from "./components/pages/Insert";
import ViewData from "./components/pages/ViewData";

const Stack = createStackNavigator();

          <NavigationContainer>
            <Stack.Navigator headerMode={false}>
              <Stack.Screen name="Insert Your data">
                 {props => (<Insert {...props} extraData={data}/>)}
              <Stack.Screen name="ViewData" component={ViewData} />
            </Stack.Navigator>
          </NavigationContainer>