将 <div> 放在 React 中的 x,y 坐标处

nop*_*rt1 5 javascript css reactjs

我有一个简单的组件,如下所示:

import React from "react";
import './MyContainer.css';

class MyContainer extends React.Component {
    constructor(props) {

        super(props);

        this.state = {

        };

    }

    showWhereClicked = (e) => {
        console.log(`you have clicked X:${e.screenX} Y:${e.screenY}`);

        // do stuff
    }



    render() {
        return (
            <div className="myContainer" onClick={this.showWhereClicked}>
                I am 500px tall.
            </div>
        );
    }
}

export default MyContainer;
Run Code Online (Sandbox Code Playgroud)

每当我点击里面的任何地方时<MyContainer />,我都会收到一条控制台消息,给出我在屏幕上点击的位置的 X 和 Y 坐标。

我希望<div>在鼠标单击的 X 和 Y 位置放置一个内部。理想情况下是一个盒子或其他东西,比如 100x100px 宽。

后来我想实现一种方法让我<div>在屏幕上自由移动这些组件。

我怎样才能做到这一点?

Twi*_*geh 7

我处理这个问题的方法是使用css in js.

position: absolute;您可以使用,top : yCoordinate和css 属性设置任何 DOM 元素的位置left : xCoordinate

// take control over the style of a component
const [style, setStyle] = useState(initialStyle); 

const setCoordinates = (x,y) => {
// You don't need whitespace in here, I added it for readability
// I would recommend using something like EmotionJS for this
    return `position:absolute;   
            left:${x}px;         
            top:${y}px;`
}

...

return(
<div 
 style = {style}
 onClick = { e => { 
     const newStyle = 
           setCoordinates(e.target.screenX,
                          e.target.screenY);
     setStyle(newStyle);
 }}
></div>)
Run Code Online (Sandbox Code Playgroud)

然后,您可以将它们设置为任何形状或形式,并且期望的结果应该是可见的。你不需要重绘任何东西,因为 DOM 没有改变,只是 css 改变了。


小智 2

   class MyContainer extends React.Component {
    constructor(props) {

        super(props);

        this.state = {
            placedDiv:{
                top:-9999px;
                left:-9999px; // hide div first
                width:100px;
                height:100px;
                position:absolute;
            }
        };

    }

    showWhereClicked = (e) => {
        console.log(`you have clicked X:${e.screenX} Y:${e.screenY}`);
        this.setState({
            placedDiv:{
                top:e.screenY + 'px'
                left:e.screenX + 'px'
            }
        })

        // do stuff
    }



    render() {
        return (
            <div className="myContainer" onClick={this.showWhereClicked}>
                I am 500px tall.
                <div style={this.state.placedDiv}></div>
            </div>
        );
    }
}

export default MyContainer;

.myContainer {
position:relative /// in CSS!!!
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要解释您做了什么才能使代码正常工作。代码转储没有用。 (2认同)