如何从React Navigation Header Ba内部调用类函数

时间:2018-11-16 23:18:22

标签: android react-native react-native-android react-navigation react-native-ios

我正在尝试在标头中调用参数化函数,但由于无法找到传递参数的方式而无法执行。

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 个答案:

答案 0 :(得分:2)

保留字thisstatic函数的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 />);
  }
}

Source