如何使子组件脱离其固定位置的父级?

时间:2020-07-18 15:04:46

标签: javascript css reactjs css-position fixed

我想在固定位置的父div之外渲染子组件。但是,子组件始终在其固定位置的父组件中呈现。以代码和图像为例,如何在与“测试1”相同的位置而不是在其固定位置的div中渲染“测试2”?我想基于浏览器视口而不是固定的父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

enter image description here

1 个答案:

答案 0 :(得分:0)

如果父母的位置固定或相对,您就不能将其移出父母。您将必须把孩子带离父母,至少要保持在同一水平。

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

如果您的孩子和父母之间有多个层次需要共享数据,则将孩子带离父母(无论您有什么想法,这都是强制性的),并使用上下文Api或状态管理进行共享数据。

最好的方法是找到一种不使用固定位置的方式,因为您的代码似乎并不复杂,可以对其进行重构以实现所需的功能。