Que*_*fat 20 javascript jquery reactjs
我试图使用jQuery在React中的一个元素中获取鼠标的相对坐标.
我的代码似乎没有工作,没有控制台错误.
码:
的index.html
<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>
Run Code Online (Sandbox Code Playgroud)
ja.js(jQuery函数)
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+")");
});
});
Run Code Online (Sandbox Code Playgroud)
零件
import React, { Component } from 'react'
import Timer from './timer'
class Level1 extends Component {
render () {
return (
<div>
<div id="gameBoard">
<img id="waldo1" src={require('../images/waldo1(1).jpg')} alt="waldo"/>
</div>
<h2 id="coords"></h2>
<Timer start={Date.now()}/>
</div>
) // return
} // render
} //component
export default Level1
Run Code Online (Sandbox Code Playgroud)
我听说jQuery没有好好反应.我的语法是正确的还是完全有更好的方法?
谢谢.
Car*_*nez 44
正如其他人所提到的,问题是当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>;
}
}
Run Code Online (Sandbox Code Playgroud)
示例笔:http://codepen.io/CarlosEME/pen/ZLVbWp