反应本机 z-index 奇怪的行为

React Native z-index strange behavior

我正在尝试编写我的自定义下拉组件,但我有一个问题,即使我将位置绝对设置为我的模态和高 z-index,下拉列表下方的组件似乎在顶部。这种行为通常不会在 Web 开发中发生,因为 position: absolute 创建了新的层堆栈。如何解决?

const Container = styled(Flex)`
  position: relative;
`

const Options = styled(Flex)`
  background-color: ${colors.white};
  position: absolute;
  z-index: 999999;
  transform: translateY(26px);
  top: 0;
  left: 4px;
  right: 4px;
  box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.16);
  border-bottom-left-radius: 26px;
  border-bottom-right-radius: 26px;
`

const Option = styled(TouchableOpacity)`
  display: flex;
  justify-content: center;
  flex-grow: 1;
  height: 52px;
  padding: 0 16px;
`

const Select = (props: Props) => {
  const { items, value, ...rest } = props

  return (
    <Container direction="column">
      <Input />
      <Options direction="column">
        <Option>
          <Text>Opcja 1</Text>
        </Option>
        <Option>
          <Text>Opcja 1</Text>
        </Option>
      </Options>
    </Container>
  )
}

export { Select }

发生这种情况是因为所有 Options 容器都具有相同的 z-index ,为了解决这个问题,您可以将 zIndex 作为道具传递给样式化组件,您传递的值取决于 dropDown 是否处于活动状态或者不是,如果它是活动的,你传递一个高的值,如果它没有传递一个低的值,这确保活动的 DropDown 总是在最上面,为了使它正常工作,它们应该是一个扩展的下拉列表或 none

const Options = styled(Flex)`
  background-color: ${colors.white};
  position: absolute;
  z-index:${({zIndex})=>zIndex} ;
  transform: translateY(26px);
  top: 0;
  left: 4px;
  right: 4px;
  box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.16);
  border-bottom-left-radius: 26px;
  border-bottom-right-radius: 26px;
`



const Select = (props: Props) => {
  const { items,index, value,isActive,setActiveDropDown, ...rest } = props

  return (
    <Container onClick{e=>setActiveDropDown(index)}  direction="column">
      <Input />
      {
         isActive
         ?<Options  zIndex={isActive?9000:1000}  direction="column">
        <Option>
          <Text>Opcja 1</Text>
        </Option>
        <Option>
          <Text>Opcja 1</Text>
        </Option>
      </Options>
        :null
      }
    </Container>
  )
}

在您的选择中:

const Wrapper=()=>{
      //initializing  activeDropDown <ith -1 means all dropdowns are collapsed 
      const [activeDropDown,setActiveDropDown]=useSate(-1)

    return <View>
         <Select setActiveDropDown={setActiveDropDown} index={0} isActive={activeDropDown==0}  />
         <Select setActiveDropDown={setActiveDropDown} index={1} isActive={activeDropDown==1}  />
         <Select setActiveDropDown={setActiveDropDown} index={2} isActive={activeDropDown==2}  />
    </View>

}