Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...