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



我有一个简单的组件,看起来像这样:

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;

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

我想在鼠标单击的X和Y位置放置一个<div>。理想情况下是一个盒子或什么的,比如100x100px宽。

稍后,我希望实现一种在屏幕上自由移动这些<div>组件的方法。

我怎样才能做到这一点?

处理此问题的方法是使用css in js

您可以设置任何具有position: absolute;top : yCoordinateleft : xCoordinatecss属性的DOM元素的位置。

// 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>)

然后,您可以将它们设置为任何形状或形式,所需的结果应该是可见的。您不需要重新绘制任何内容,因为DOM没有更改,只更改了css。

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!!!
}

最新更新