之前用vue做日程管理组件的时候,用到了点击拖拽的效果,即点击元素,鼠标移动到哪里,元素移动到哪里,鼠标松开,拖拽停止,现在在弄react,于是也在想实现这个效果,经过一番折腾,效果出来了,代码如下:

<body>
<div ></div>
</body>
<script type="text/babel">
    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 (
                <div>
                    <img ref={item => 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}}/>
                </div>

            )
        }
    }

    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 (
                <div style={{height: "100vh"}} onMouseMove={this.movePosition.bind(this)}>
                    {this.props.render(this.state)}
                </div>
            )
        }
    }

    class Result extends React.PureComponent {
        render() {
            return (
                <div>
                    <Position render={mouse =>
                        (<Cat mouse={mouse}/>)}>
                    </Position>
                </div>
            )
        }
    }

    ReactDOM.render(
        <Result></Result>,
        document.getElementById("test")
    )
</script>

  react实现的点击拖拽元素效果

效果如图,cat猫咪的图片自己找,整体还不错,不会的可以私信我...

相关文章:

  • 2021-11-28
  • 2021-11-21
  • 2022-12-23
  • 2021-11-28
  • 2021-12-02
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-15
  • 2022-12-23
  • 2022-01-24
  • 2021-12-23
  • 2022-12-23
  • 2020-06-10
  • 2022-12-23
相关资源
相似解决方案