Javascript 按React键时触发多个事件
我对这里的反应还不熟悉,我试图理解下面这个简单代码的内容:Javascript 按React键时触发多个事件,javascript,reactjs,Javascript,Reactjs,我对这里的反应还不熟悉,我试图理解下面这个简单代码的内容: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export default class MainView extends Component { constructor(props) { super(props); this.state = { role: ''
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class MainView extends Component {
constructor(props) {
super(props);
this.state = {
role: ''
};
this._keyPressed = this.keyPressed.bind(this);
}
render() {
const { role } = this.state;
document.addEventListener("keyup", this._keyPressed.bind(this));
return (
<div className="container">
<input id="role" value={role} type="text"
onChange={
(newValue) => this.setState({
role: newValue.target.value
})
}
/>
</div>
);
}
keyPressed(event) {
console.log(event);
}
}
if (document.getElementById('mainview')) {
ReactDOM.render(<MainView />, document.getElementById('mainview'));
}
将文本添加到输入框时,键盘事件会触发多次,具体取决于当前输入长度。更具体地说,事件被激发n次,其中n是输入被修改的实际次数,计算每个添加/删除的字符,例如:
将“a”字符添加到输入:
KeyboardEvent {isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
然后添加“v”字符:
删除最后(v)个字符:
尽管我已经意识到输入元素的KeyboardEvent事件和onChange事件之间存在着某种关系,但我还是有点困惑,无法正确地理解这是如何工作的
非常感谢您的解释。建议不要使用本机事件处理程序,如使用addEventListener创建的本机事件处理程序 通常,应该只向组件添加事件处理程序,就像onChange一样
这里发生的是,每次输入字符时,onChange侦听器都会更改状态,因此会重新呈现组件。由于在渲染函数中将监听器添加到keyup,因此每次渲染时都会添加一个新的监听器。这是因为每次按keyOk键时组件都会重新渲染,但为什么要连续4次呢?即使在输入不聚焦的情况下按下另一个键,也会发生这种情况。
KeyboardEvent {isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "v", code: "KeyV", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "v", code: "KeyV", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "v", code: "KeyV", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "Backspace", code: "Backspace", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "Backspace", code: "Backspace", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "Backspace", code: "Backspace", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "Backspace", code: "Backspace", location: 0, ctrlKey: false, …}