首页 > 解决方案 > React Native:当使用 zIndex 绝对定位时,TouchableOpacity onPress 不会触发

问题描述

我正在开发一个 React Native 项目,TouchableOpacity 当元素具有以下 CSS 时,我正在努力获得触发它的按下功能:

position: absolute;
z-index: 2;

下面是代码:

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { View } from 'react-native';

const StyledImage = styled.Image`
  height: 24px;
  width: 32px;
`;

const MenuContainer = styled.View`
  display: flex;
  position: absolute;
  background-color: #2d2d2d;
  height: ${Dimensions.get('screen').height};
  width: ${Dimensions.get('screen').width * 0.75};
  z-index: 2;
  margin-left: -8px;
  margin-top: -16px;
`;

const ProfileSectionContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-bottom: 24px;
`;

const HeadingContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 20px;
`;

const CloseButton = styled(Body1)`
  font-size: 18px;
`;

const MenuItemsContainer = styled.View`
  padding: 0 20px;
`;

const SignOutContainer = styled.View`
  position: absolute;
  bottom: 100;
  flex: 1;
  left: 40%;
`;

const handleLogout = navigate => async () => {
  await logout()
  redirectToLogin(navigate)();
};

const toggleIsOpen = (isOpen, setIsOpen) => () => setIsOpen(!isOpen);

const Menu = ({ isOpen, setIsOpen, navigate }) => (
  <MenuContainer>
    <HeadingContainer>
      <View>
        <Body1 color="#fff">New App</Body1>
      </View>
      <View>
        <TouchableOpacity onPress={toggleIsOpen(isOpen, setIsOpen)}>
          <CloseButton color="#fff">X</CloseButton>
        </TouchableOpacity>
      </View>
    </HeadingContainer>
    <ProfileSectionContainer>
      <ProfileSection />
    </ProfileSectionContainer>
    <MenuItemsContainer>
      <MenuItems menuItems={[{ text: 'Link 1' }, { text: 'Link 2' }]} />
    </MenuItemsContainer>
    <SignOutContainer>
      <TouchableOpacity onPress={handleLogout(navigate)}>
        <Body1 color="#fff">Sign Out</Body1>
      </TouchableOpacity>
    </SignOutContainer>
  </MenuContainer>
);

我查看了所有 StackOverflow 链接,但似乎没有一个解决方案有效。

我目前正在使用 React Native 0.59.8,这是撰写此问题时的最新版本。

编辑:TouchableOpacity当前不起作用的Sign Out是位于底部的按钮MenuContainer。我确实有另一个TouchableOpacity包含X关闭菜单的菜单,而且效果很好。

标签: androidreact-native

解决方案


试试这个绑定选项:

constructor(props) {
    super(props);
    this.toggleIsOpen = this.toggleIsOpen.bind(this);
    this.handleLogout = this.handleLogout.bind(this);
}

推荐阅读