this.props.navigation.navigate() is undefined

KO9 :

I am using createStackNavigator like this.

const ChatStack = createStackNavigator({
  Profiles: Profiles,
  ChatScreen: ChatScreen
})

const RootChatStack = createStackNavigator({
  Home: ChatStack,
  ModalScreen: ProfileModalScreen
},{
    mode: 'modal',
    headerMode: 'none',
  })

In Profiles I use props.navigation.navigate('ChatScreen',{name: item.content }) to go to ChatScreen.

And In ChatScreen

class Example extends React.Component {
  static navigationOptions = ({navigation}) => {
    return {
    title: navigation.getParam('name', ''),
  };
 ...
  renderModal() {
    this.props.navigation.navigate('ModalScreen')
  }
 ...
 }

I can set title using navigationOptions, but when I use this.renderModal(), It gives me Error

undefined is not an object (evaluating '_this2.props.navigation')

How I can use navigation.navigate inside Example Component?

Arno :

If you're using class based react components you have to bind additional functions in your components to the instance. You would do so by explicitly binding this to each additional function in your component (react functions like render() are already bound).

This is the key line in the snippet below: this.renderModal = this.renderModal.bind(this);

class Example extends React.Component {
  constructor(props) {
    super(props);

    this.renderModal = this.renderModal.bind(this);
  }

  renderModal() {
    this.props.navigation.navigate('ModalScreen');
  }

  ...
 }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390964&siteId=1