Search code examples
react-nativenavbarreact-native-router-flux

router-flux navbar button this.function is not a function


I implemented in my router-flux nav bar a right button like this:

  static renderRightButton = (props) => {
          return (
              <TouchableOpacity onPress={() => this.getCurrentPosition()} style={{bottom: 4, right: 8}}>
                  <Icon name='ios-locate-outline' style={{color: 'white'}} />
              </TouchableOpacity>
          );
    }

But If I click on my button I get this error :this.5.getCurrentPosition is not a function

I declare my function in the constructor with this.getCurrentPosition = this.getCurrentPosition.bind(this)


Solution

  • You're using a static method, which means you don't have access to this, which only works for instances.

    So you can either

    1) remove static

    renderRightButton = () => {
              return (
                  <TouchableOpacity onPress={() => this.getCurrentPosition()} style={{bottom: 4, right: 8}}>
                      <Icon name='ios-locate-outline' style={{color: 'white'}} />
                  </TouchableOpacity>
              );
        }
    

    2) or pass getCurrentPosition to the render method as a parameter.

    static renderRightButton = (props, getCurrentPosition) => {
              return (
                  <TouchableOpacity onPress={getCurrentPosition} style={{bottom: 4, right: 8}}>
                      <Icon name='ios-locate-outline' style={{color: 'white'}} />
                  </TouchableOpacity>
              );
        }