简体   繁体   English

"<i>How to center react-draggable element on start?<\/i>如何在开始时将反应可拖动元素居中?<\/b> <i>(modal, div)<\/i> (模态,div)<\/b>"

[英]How to center react-draggable element on start? (modal, div)

How to center react-draggable element on start?如何在开始时将反应可拖动元素居中? I have a modal that is wrapped by react-draggable a component.我有一个由 react-draggable 组件包装的模态。 I would like to after the modal is open, center his position in a browser.我想在模式打开后,将他的位置放在浏览器中。 I try pass to a defaultPosition a percentage value but I'm not able to pass percentage defaultPostion={{ x: 50%, y: 50% };}<\/code> but without result.我尝试将百分比值传递给 defaultPosition,但我无法传递百分比defaultPostion={{ x: 50%, y: 50% };}<\/code>但没有结果。

"

I found solution but I don't have access no more.我找到了解决方案,但我无法再访问了。 The solution is to change dynamically position for defaultPosition: get position of element that has been clicked and dynamically calculate center of the screen.解决办法是动态改变defaultPosition的位置:获取被点击元素的位置,动态计算屏幕中心。

使用 css3,最好和最简单的反应解决方案:

.center { margin: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

You can't use CSS transform because defaultPosition replace it.您不能使用 CSS 转换,因为defaultPosition替换了它。

You can use margin , I normally use this solution:您可以使用margin ,我通常使用这个解决方案:

import React, { useState, useEffect } from "react"
import Draggable from 'react-draggable';

function MyComponent() {

    const [boxSize, setBoxSize] = useState({ w: 0, h: 0 });

    useEffect(() => {

        setBoxSize({
            w: document.querySelector('.container').clientWidth / -2,
            h: document.querySelector('.container').clientHeight / -2
        });

    }, []);

    return (

        <Draggable>
            <div style={{
                marginLeft: boxSize.w,
                marginTop: boxSize.h
            }} className="container">

                {/* ... */}

            </div>
        </Draggable>

    );

}

export default MyComponent;

尝试在百分比周围使用引号,例如defaultPosition={{ x: '50%', y: '50%' }}

React draggable has an option named positionOffSet which gives us a chance to set the initial offset of the draggable element. React draggable 有一个名为positionOffSet的选项,它让我们有机会设置可拖动元素的初始偏移量。 This is different than the defaultPosition and accepts %value .这不同于defaultPosition并接受%value You can check the React Draggable docs for details.您可以查看 React Draggable 文档以获取详细信息。

<Draggable positionOffset={{ x: '-50%', y: '-50%' }}}>
  <div className='myElement'>
    This is my draggable element
  </div>
</Draggable/>

Now, all we need to do is to add few styles to our element like so:现在,我们需要做的就是向我们的元素添加一些样式,如下所示:

.myElement{z-index:999; position: absolute; top: 50%; left: 50%;}

This will center the modal element in the middle of the page, no matter what dimensions it has.这将使模态元素在页面中间居中,无论它有什么尺寸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM