Как вызвать функцию класса из заголовка React Navigation Header Ba

Я пытаюсь вызвать параметризованную функцию в заголовке, но не могу, так как не могу найти способ передать параметр.

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 />);
}

}
4
0
1 181
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Зарезервированное слово this ничего не значит в контексте static функции navigationOptions, поэтому вы не можете использовать его там для вызова searchFunction.

Есть способ добавить параметры к объекту navigation, чтобы вы могли получить их в статической функции navigationOptions.

Вы можете добавить searchFunction как параметр объекта navigation и передать его атрибуту onChangeText.

Реализация выглядит так:

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 />);
  }
}

Источник

Я дам ему попробовать. Спасибо за ответ.

Umar 18.11.2018 21:46

Отлично :) Пожалуйста. Вы должны отметить этот ответ как принятый, чтобы другие люди увидели, что на этот вопрос есть принятый ответ.

HedeH 19.11.2018 06:56

Другие вопросы по теме