【问题标题】:How to render child components out of its fixed position parent?如何将子组件从其固定位置的父组件中渲染出来?
【发布时间】:2020-07-18 23:22:33
【问题描述】:

我想在其固定定位的父 div 之外呈现子组件。但是,子组件总是在其固定位置的父组件中呈现。以代码和图像为例,如何将“Test 2”渲染在与“Test 1”相同的位置,而不是在其固定位置的div内?我想基于浏览器视口而不是其固定的父 div 来渲染它。提前致谢!

import React,{useState} from 'react'

function Testing() {
    const [isCLicked, setIsCLicked] = useState(false)
    return (
        <div style={{
            position:'relative',
            width:'100vw',
            height:'100vh',
            backgroundColor:'lightblue',
        }}>
            <p style={{
                position:'absolute',
                top:'10%',
                left:'10%',
                backgroundColor:'black',
                color:'white'
            }}>Test 1</p>

            <div style={{
                position:'fixed',
                top:0,
                left:'50%',
                height:'100vh',
                width:'10vw',
                backgroundColor:'green'
            }}>
                <button onClick={()=>setIsCLicked(true)}>create new text box</button>
                {isCLicked && 
                    <p style={{
                        position:'absolute',
                        top:'10%',
                        left:'10%',
                        backgroundColor:'black',
                        color:'white'
                    }}>Test 2</p>
                }
            </div>

        </div>
    )
}

export default Testing

【问题讨论】:

    标签: javascript css reactjs css-position fixed


    【解决方案1】:

    如果您的父母有固定或相对位置,您不能将您的孩子从父母身边移走。你必须让你的孩子离开你的父母,至少把它放在同一水平上。

    现在,如果您的孩子依赖于您父母拥有的某些数据,那么您可以使用prop drilling 将这些数据发送给他们共同的父母。这样您就可以在这两者之间共享数据。

    如果您的孩子和父母之间有多个级别需要共享数据,则将孩子从父母中取出(这是强制性的,无论您有什么想法)并使用上下文 Api 或状态管理来共享数据。

    最好的办法是想办法不使用固定位置,因为你的代码看起来并不复杂,可以通过重构实现你想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多