简体   繁体   中英

How to pass parameters between two screens in react native?

Please, do not hurry to close this question as duplicate. I have read the official documentation here and so fa I have managed to pass successfully parameters between screens. There is som problem with my current case, and the solution is not obvious for me.

I have two screens. The first is called "Feed" and it belongs to bottom tab navigator. From the "Feed" screen I want to be able to navigate to "Comments" screen which is part of stack navigator.

I am able to successfully navigate between both screens, however, for some reason I am not able to pass any parameters when I navigate from "Feed" to "Comments".

Part of my "Feed" screen where I press "comments" icon:

      <TouchableOpacity
          onPress={() => {
            console.log("passing param id: ", id);
            navigation.navigate("Comments", { id: id });
          }}
        >
          <FontAwesome name="comment-o" size={30} color="#0047AB" />
        </TouchableOpacity>

What I see on the console:

passing param id: some_id_whic_does_not_matter

I manage to successfully navigate to my "Comments" screen. Part of my "Comments" screen:

const CommentsScreen = (props) => {
  console.log("Comments Screen: ");
  console.log("comments: ", props);

What I see on the console for the route object:

route": Object {
    "key": "Comments-some-key",
    "name": "Comments",
    "params": undefined,
  }

Can you tell me what I am doing wrong?

Where I am currently located on NetworkNavigator tab, and from there I want to navigate to the Comments screen.

I still dont see where the issue is?

I think we access params via route I mean

const CommentsScreen =({route})=>{
    const {id} = route.params;
    console.log(id);
...}

You can access your passed params via following

const CommentsScreen = (props) => {
  console.log("Comments Screen: ");
  console.log("comments: ", props.route.params.id);

props.route.params

It contains the object you passed in

navigation.navigation('screenname', {
...this object...
});

you can extract the data by using the same keys.

Example

navigation.navigation('screenname', {
  id: '1',
  name: 'Adam',
  age: 12
});

//Then you can access via 

  console.log("id: ", props.route.params.id);
  console.log("name: ", props.route.params.name);
  console.log("age: ", props.route.params.age);

I found the answer to my question here: https://reactnavigation.org/docs/5.x/nesting-navigators#passing-params-to-a-screen-in-a-nested-navigator

So in my case:

navigation.navigate("Root Navigator", {
              screen: "Comments",
              params: { id: id },
            });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM