【问题标题】:Struggling using zIndex to order views努力使用 zIndex 对视图进行排序
【发布时间】:2021-11-29 06:10:54
【问题描述】:

我正在尝试将一个组件加载到另一个组件之上。在我的演示中,我有两个使用滑块按钮有条件地呈现的屏幕(我会使用一个简单的文本按钮,但我想确保动画有效)。屏幕 1 只是一个灰色屏幕,屏幕 2 是正在渲染的 react 原生地图屏幕。

我希望滑块按钮位于地图顶部。我需要地图是整页的。最初我尝试使用 zIndex 但这不起作用。

我有一个工作演示 here

App.js

export default class Home extends React.Component {
 
  constructor(props) {
    super(props)
    this.state ={
      visible: true,
      whichComponentToShow: 'Screen1'
    };
}

goToMap = () => {
  this.setState({whichComponentToShow: 'Screen2'})
}
goToList = () => {
  this.setState({whichComponentToShow: 'Screen1'})
}

  render(){

    const SliderRender = (
      <Slider
        renderMap={this.goToMap.bind(this)}
          renderList={this.goToList.bind(this)}
          key="slider"
          style={{zIndex: 10}}
         />
      );
    
     if(this.state.whichComponentToShow === 'Screen1'){
      return(
       <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>  
        
        {SliderRender}

          <ListHome
            renderMap={this.goToMap.bind(this)}
            renderList={this.goToList.bind(this)}
          />
        </View>
      );
    }
    else if(this.state.whichComponentToShow === 'Screen2'){
      return(
       <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>

        <MapHome
          renderMap={this.goToMap.bind(this)}
          renderList={this.goToList.bind(this)}
          
        />

        {SliderRender}
 
       </View>
      );
    }
 }
 }
 

【问题讨论】:

    标签: reactjs react-native react-native-maps


    【解决方案1】:

    您可以使用View 和position: absolute 来包裹滑块按钮。

    render() {
      const { whichComponentToShow } = this.state;
    
      return(
        <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>
          {whichComponentToShow === 'Screen1' && <ListHome />}
          {whichComponentToShow === 'Screen2' && <MapHome />}
          <View style={{position: 'absolute', top: 0, left: 0, right: 0}}>
            <Slider
              renderMap={this.goToMap}
              renderList={this.goToList}
            />
          </View>
        </View>
      );
    }
    

    【讨论】:

    • 我仍然希望地图是整个页面。
    • 明白。我已经更新了答案。
    • 视觉上看起来很完美。我唯一注意到的是动画似乎停止工作。您可以在 Maphome 之前渲染它以查看动画的工作方式。关于为什么向 sliderRender 添加视图会导致动画停止工作/重新渲染的任何想法?
    • 这是因为滑块组件正在屏幕之间重新渲染。所以active 状态总是false。它在初始代码中工作的原因是 React 理解那些是相同的组件并重用滑块而不卸载它。我已再次更新代码以解决此问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 2013-04-22
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多