【问题标题】:How to call a class function from inside a React Navigation Header Ba如何从 React Navigation Header Ba 内部调用类函数
【发布时间】:2018-11-16 23:18:22
【问题描述】:

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

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

}

【问题讨论】:

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


    【解决方案1】:

    保留字thisnavigationOptions 函数的static 上下文中没有任何意义,因此您不能在那里使用它来调用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

    【讨论】:

    • 我会试一试的。感谢您的回答。
    • 太棒了 :) 不客气。您应该将此答案标记为已接受,以便其他人看到此问题的答案已被接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    相关资源
    最近更新 更多