为什么具有 onPress={action} 的 navigationOptions => headerLeft 中的按钮不起作用?反应本机

Noo*_*Dev 1 react-native react-navigation

我在 React Native 工作,实际上我正在尝试实现一种自定义侧边菜单以避免 DrawerMenu 实现,我尝试只是在 headerLeft 上添加一个图标,但它不起作用,按下时它没有任何动作。

class HomeScreen extends React.Component {
    static navigationOptions = {
        headerTitle: ('',
            <Image style={{ width: 150, height: 40 }}
                source={require('./images/logo.png')}
            />
        ),
        headerLeft: (
            <TouchableHighlight onPress={this._logout}>
                <Image style={{ width: 40, height: 40 }}
                    source={require('./images/hamburger_icon.png')}
                />
            </TouchableHighlight>
        ),
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试将按钮放置在 mapView 中时也是如此。

<View style={{ flex: 1 }}>

    <MapView
        ...
    >
        <Button onPress={this._logout} title="Logout" />
    </MapView>

</View >
Run Code Online (Sandbox Code Playgroud)

但是在视图中实现的相同按钮效果很好。

<View style={{ flex: 1 }}>
     <Button onPress={this._logout} title="Logout" />
    <MapView
        ...
    >
        ...
    </MapView>

</View >
Run Code Online (Sandbox Code Playgroud)

我看到了一个使用一些组件作为 DidMount 的解决方案,但我不确定如何实现它。

提前致谢。

And*_*rew 5

您正在尝试this._logout在静态方法中访问。不幸的是,您已经发现这行不通。

可以将函数传递给标头。您可以在此处阅读有关将函数传递给标头组件的更多信息

这是相当直接的。

  1. 在您的 componentDidMount 中setParams使用您的注销功能
  2. 在您headerLeft使用该getParam属性访问您的功能时。
  3. 注意我们是如何访问导航栏中的 navigationOptions

下面是一个例子:

class HomeScreen extends React.Component {

  static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: ('',
      <Image style={{ width: 150, height: 40 }}
        source={require('./images/logo.png')}
      />
      ),
      headerLeft: (
        <TouchableHighlight onPress={navigation.getParam('logout')}>
          <Image style={{ width: 40, height: 40 }}
            source={require('./images/hamburger_icon.png')}
          />
        </TouchableHighlight>
      )
    };
  };

  _logout = () => {
    alert('logout');
  }

  componentDidMount () {
    this.props.navigation.setParams({ logout: this._logout });
  }

  render() {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)