Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

react-navigation - navigating from child component

I have a leaderboard which calls a component and passes it data to it like so:

   _renderItem =({item}) => (
    <childComponent
        key={item._id}
        id={item._id}
        name={item.name}
    />
   );

And inside the childComponent I try do this:

    <TouchableOpacity onPress={() => this.props.navigation.navigate("Profile", { id: this.props.id})} >
       <View>
         <Right>
              {arrowIcon}
         </Right>
       </View>
    </TouchableOpacity>

Where I am hoping that it will then go to the profile page and grab the correct data based on the id passed to it. The issue is that when I click the arrow to go to the profile page I get the error Cannot read property 'navigate of undefined. I have put both the leaderboard and childComponent in my HomeDrawerrRoutes.js and MainStackRouter.js. Any help would be great, thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is an easy Solution for this,

use withNavigation . it's a higher order component which passes the navigation prop into a wrapped Component.

example child component

import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';

class ChildComponent extends React.Component {
  render() {
    <View
      onPress = {()=> this.props.navigation.navigate('NewComponent')}>
     ... logic
    </View>

  }
}

// withNavigation returns a component that wraps ChildComponent and passes in the
// navigation prop
export default withNavigation(ChildComponent);

for more details : https://reactnavigation.org/docs/en/connecting-navigation-prop.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...