我正在用 Reactjs 编写一个简单的光标记录网页,问题是记录数组仅在我单击按钮时更新,而我的意图是在鼠标移动时不断更新。逻辑实际上在原始 javascript 上运行良好,一定有一些关于反应事件如何工作的东西,我弄错了。编码:
import React, {Component} from 'react';
class MouseRecord extends Component {
constructor(props) {
super(props);
this.state = {
records: [],
displayMessage: false
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this.state.records);
this.setState(prevState => ({
//records: [],
displayMessage: !prevState.displayMessage
}));
}
handleMouseMove(e) {
e.preventDefault();
if (this.state.records.length <= 100000){
this.setState(prevState => ({
records: prevState.records.concat([{
cor_X: e.clientX,
cor_Y: e.clientY,
width: window.innerWidth,
height: window.innerHeight,
timestamp: new Date().toUTCString()
}])
}));
}
}
componentDidMount() {
document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
}
componentWillUnmount() {
document.removeEventListener('mousemove', (e) => this.handleMouseMove(e));
}
render(){
return(
<div className="box">
<button onClick={this.handleClick}>Click to retrieve mouse records</button>
<div>
{this.state.displayMessage ? this.state.records.length > 0 ? this.state.records.map((record) => {
return (
<div key={this.state.records.indexOf(record)}>
<p>client X: {record.cor_X}</p>
<p>client Y: {record.cor_Y}</p>
<p>Window width: {record.width}</p>
<p>Window height: {record.height}</p>
<p>Timestamp: {record.timestamp}</p>
<br/>
<br/>
</div>
);
}) : null : null}
</div>
</div>
);
}
}
export default MouseRecord;