在React中获取鼠标坐标

时间:2017-02-11 23:31:42

标签: javascript jquery reactjs

我试图使用jQuery在React中的一个元素中获取鼠标的相对坐标。

我的代码似乎没有工作,并且没有控制台错误。

代码:

的index.html

[enddata]

ja.js(jQuery函数)

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="stylesheets.css" >
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script src="ja.js" type="text/javascript"></script>

    <title>Where's Waldo</title>
  </head>

    <div id="root"></div>

  </body>
</html>

组件

jQuery(function($) {
 var x,y;
 $("#waldo1").mousemove(function(event) {
     var offset = $(this).offset();
     x = event.pageX- offset.left;
     y = event.pageY- offset.top;
     $("#coords").html("(X: "+x+", Y: "+y+")");
 });
});

我听说jQuery没有好好反应。我的语法是正确的还是完全有更好的方法?

谢谢。

4 个答案:

答案 0 :(得分:37)

正如其他人所提到的,问题是当jQuery尝试附加事件监听器时,react没有将组件呈现给DOM。

你根本不需要jQuery,更好的方法是使用React事件:

class Application extends React.Component {
  constructor(props) {
    super(props);

    this.state = { x: 0, y: 0 };
  }

  _onMouseMove(e) {
    this.setState({ x: e.screenX, y: e.screenY });
  }

  render() {
    const { x, y } = this.state;
    return <div onMouseMove={this._onMouseMove.bind(this)}>
      <h1>Mouse coordinates: { x } { y }</h1>
    </div>;
  }
}

示例笔:http://codepen.io/CarlosEME/pen/ZLVbWp

答案 1 :(得分:2)

这应该适合你:

<head>

答案 2 :(得分:0)

问题(以及jQuery和反应不顺利的原因)很可能是当jQuery试图附加事件监听器时,反应没有呈现给DOM元素。

您应该使用reacts方法查看附加事件侦听器。 https://facebook.github.io/react/docs/events.html#mouse-events

答案 3 :(得分:0)

你可以试试这个:

import React, { Component } from "react";

class ClassCursorPosition extends Component {
  constructor(props) {
    super(props);
    this.state = {
      x: 0,
      y: 0
    };
  }

  logMousePosition = e => {
    this.setState({
      x: e.clientX,
      y: e.clientY
    });
  };
  componentDidMount() {
    window.addEventListener("mousemove", this.logMousePosition);
  }
  render() {
    return (
      <div>
        X- {this.state.x} Y - {this.state.y}
      </div>
    );
  }
}
相关问题