Bring View on top of Modal using zIndex style with

2020-06-30 05:49发布

问题:

zIndex has been introduced recently to React-Native to change the position of a View in the stack of layers.

Although, I'm not able to bring a View on top of a Modal component.

My code looks like this:

render() {
  return (
    <View>
      <Modal visible>
        {props.children}
      </Modal>
      <View style={{ zIndex: 1000 }}>
        <Text>Loading...</Text>
      </View>
    </View>
  );
}

I guess I could stop using <Modal> and create a regular animated <View> that would behave like the Modal, but I'd rather find another solution.

Any idea?

回答1:

No amount of zIndex manipulation will bring something above a react-native Modal, unfortunately. The Modal component is a native view that sits on top of the rest of your react-native application. The only way to put something above it is to put something in the modal itself, or alternately to use a js only implementation of a Modal.

Incidentally, the react-native-community version of modal is also built on the react-native modal, so would have the same issue. There's a discussion about different js implementation here: https://github.com/react-native-community/react-native-modal/issues/145



回答2:

Not possible with modal. As the modal should always shown regardless of whatever the zIndex is given to it and other components in the screen

It will always shown you unless you make visible=false

To implement what you want. You could use a absolutely positioned view with some zIndex trick to move this view back and front.

render() {
  return (
    <View>
       <View style={{position:'absolute',top:0,bottom:0,left:0,right:0,zIndex:visible?-1:2}}>
          {props.children}
       </View>
       <View style={{ zIndex: 1 }}>
          <Text>Loading...</Text>
       </View>
     </View>
  );
}


回答3:

You have to change the z-index of the modal not the one of the view (and a z-index of value 1 would suffice):

render() {
  return (
    <View>
      <Modal visible style={{ zIndex: 1 }}>
        {props.children}
      </Modal>
      <View>
        <Text>Loading...</Text>
      </View>
    </View>
  );
}

An element with a larger z-index generally covers an element with a lower one (MDN docs).

EDIT:

Another solution is to change the order of the elements:

render() {
  return (
    <View>
      <View>
        <Text>Loading...</Text>
      </View>
      <Modal visible>
        {props.children}
      </Modal>
    </View>
  );
}

With this solution you don't need z-index because the modal is already on top of the view.