android - 如何从 React Navigation Header Ba 中调用类函数

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

我试图在 header 中调用参数化函数,但无法找到传递参数的方法。

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

}

最佳答案

保留字 thisnavigationOptions 函数的 static 上下文中没有任何意义,所以你不能在那里使用它来调用搜索函数

有一种方法可以将参数添加到 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

关于android - 如何从 React Navigation Header Ba 中调用类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346613/

相关文章:

react-native - 任务 :react-native-screens:javaPreCompileDebug error in React Navigation 5. x

javascript - TypeError : e. _panGestureHandler.current.setNativeProps 不是函数

java 不运行 if 结构在 onclick 监听器内

android - Activity 加载时的调用方法,Android

android - android 中的自定义字体(适用于整个应用程序)

java - 获取 RecyclerView.ViewHolder 中的上下文

android - 适用于 iOS、Android、React Native 的 Web 音频 API?

react-native - 如何按组显示日期,例如 Whatsapp 聊天屏幕?

ios - 为什么我无法查询可用的应用内购买

reactjs - 抽屉导航器 : Change Text Color