【问题标题】:React: Absolute Position In Child ComponentsReact:子组件中的绝对位置
【发布时间】:2023-02-23 09:43:58
【问题描述】:

简介:我有一个 React 组件结构,看起来像这样。

-- 父组件.tsx --

<div>Some Content Here</div>
<ChildComponent/>
<div style={{ position: "relative", zIndex: "1" }}>
    Some Other Content -- should be covered when the absolutely positioned content
    inside of ChildComponent renders on the screen!
</div>

-- 子组件.tsx --


/* at the top of my render method */

const [booleanCondition, setBooleanCondition] = useState(false);
const toggleBooleanCondition = () => { setBooleanCondition(!booleanCondition); };

...
/* much later, in the return value of render method */

<div style={{ position: "relative", zIndex: "2" }}>
    Some Content Here, capable of calling toggleBooleanCondition()
    { booleanCondition ?
        <div style={{ position: "absolute", width: "400px", height: "400px" }}>
            Some Content Here. Should definitely cover the bottom <div> in parent!
        </div>
      : <></>
</div>

切换逻辑绝对有效。问题是,我希望 ChildComponent.tsx 中的 div 完全位于 ParentComponent.tsx 中的 div 之上,后者具有较小的 z-index。然而,情况并非如此:下面的屏幕截图显示元素以随机顺序呈现。

我觉得这个问题可能是由于不同的组件为它们自己的 z-index 分配了不同的含义。无论我如何使用 position: relative 和 z-index: ,似乎都没有改变。有谁知道这个问题的可靠解决方案?

【问题讨论】:

    标签: reactjs css-position absolute


    【解决方案1】:

    我的 CSS 背景不是白色的。哈哈。

     <div style={{ position: "absolute", width: "400px", height: "400px", backgroundColor: "white"}}>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2016-08-18
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多