之前用vue做日程管理组件的时候,用到了点击拖拽的效果,即点击元素,鼠标移动到哪里,元素移动到哪里,鼠标松开,拖拽停止,现在在弄react,于是也在想实现这个效果,经过一番折腾,效果出来了,代码如下:
let catDom = "";
let catSwitch = false;
class Cat extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
initSwitch: false
}
}
componentDidMount() {
catDom = this.cat
}
toggleOpen(result,event) {
this.setState({
initSwitch: result
}, () => {
catSwitch = this.state.initSwitch;
console.log(this.state.initSwitch, result);
});
event.preventDefault()
}
render() {
const mouse = this.props.mouse;
return (
this.cat = item} src="./../imgs/cat.jpg"
onMouseDown={this.toggleOpen.bind(this, true)} onMouseUp={this.toggleOpen.bind(this, false)}
style={{position: "absolute", left: mouse.x, top: mouse.y}}/>
)
}
}
class Position extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
x: 0,
y: 0
}
}
movePosition(event) {
if (catDom && catSwitch) {
this.setState({
x: event.clientX - catDom.width / 2,
y: event.clientY - catDom.height / 2
})
} else {
return null;
}
}
render() {
return (
{this.props.render(this.state)}
)
}
}
class Result extends React.PureComponent {
render() {
return (
()}>
)
}
}
ReactDOM.render(
,
document.getElementById("test")
)
效果如图,cat猫咪的图片自己找,整体还不错,不会的可以私信我...