4

I am trying to call a parameterized function in a header but could not as I am unable to find to way to pass parameter.

class MyScreen extends React.Component {

static navigationOptions = ({ navigation }) => 
{
    headerLeft: (
        <SearchBar 
         placeholder="Search"
         round
         onChangeText={text => this.searchFunction(text)}
        />
    )
};

*searchFunction(text) 
{
    alert( text + ' searched succesfully');
}*

componentDidMount() 
{
  **//I would need implementation here**
}

render() 
{
    return (<View />);
}

}

1 Answer 1

3

The reserved word this means nothing in the static context of the navigationOptions function, So you can't use it there to call the searchFunction.

There's a way to add params to the navigation object so you can get them in the navigationOptions static function.

You can add the searchFunction as a navigation object param and pass it to the onChangeText attribute.

The implementation looks like this:

class MyScreen extends React.Component {

  // Pass the searchFunction from the navigation params to the `onChangeText` attribute.
  // It should be triggered with the `text` argument. 
  static navigationOptions = ({ navigation }) => 
  {
    headerLeft: (
      <SearchBar 
       placeholder="Search"
       round
       onChangeText={navigation.getParam('searchFunc')} 
      />
    )
  };

  // Use arrow function to bind it to the MyScreen class.
  // (I'm not sure you have to do it like this, try to use it as a normal function first)
  searchFunction = (text) => {
    alert( text + ' searched succesfully');
  }

  // Add the `searchFunction` as a navigation param:
  componentDidMount() {
    this.props.navigation.setParams({searchFunc: this.searchFunction})
  }

  // Since we pass a class function as a param
  // I believe it would be a good practice to remove it 
  // from the navigation params when the Component unmounts.
  componentWillUnmount() {
    this.props.navigation.setParams({searchFunc: null})
  }

  render() {
    return (<View />);
  }
}

Source

Sign up to request clarification or add additional context in comments.

1 Comment

I will give it a try. Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.