我是React的新手,并试图了解这个简单代码的用途:
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'));
}
问题在于,按键盘上的随机键会导致预期的行为,例如:
KeyboardEvent {isTrusted: true, key: "h", code: "KeyH", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "d", code: "KeyD", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "g", code: "KeyG", location: 0, ctrlKey: false, …}
将文本添加到输入框时,会根据当前输入长度多次触发KeyboardEvent。更具体地说,事件被触发n次,其中n是输入被修改的实际次数,计算每个添加/删除的char,例如:
添加&#34; a&#34; char输入:
KeyboardEvent {isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
KeyboardEvent {isTrusted: true, key: "a", code: "KeyA", location: 0, ctrlKey: false, …}
然后添加&#34; v&#34;炭:
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, …}
删除last(v)char:
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, …}
尽管我已经设法意识到KeyboardEvent事件和输入元素的onChange事件之间存在关系的存在,我有点困惑,我无法弄清楚这是怎么回事。真的很有效。
任何解释都应该非常感谢,谢谢。
答案 0 :(得分:1)
React建议不要使用像使用addEventListener创建的本机事件处理程序。
通常,您应该只向组件添加事件处理程序,就像使用onChange一样。
这里发生的是你的onChange监听器每次输入一个字符时都会改变状态,因此重新渲染组件。由于您在render函数中将侦听器添加到keyup,因此在每次渲染时都会添加一个新的。