Javascript 如何在 React.js 中触发按键事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28102746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trigger keypress event in React.js
提问by Piyush
I'm new to React.js. I'm trying to trigger keypress event for text div.
我是 React.js 的新手。我正在尝试为文本 div 触发按键事件。
Here is text box code for which I want to execute keypress trigger.
这是我要执行按键触发器的文本框代码。
<div id="test23" contenteditable="true" class="input" placeholder="type a message" data-reactid="137">Hii...</div>
and keypress method is:
和按键方法是:
onKeyPress: function(e) {
return "Enter" == e.key ? "Enter key event triggered" : void 0)
}
I tried it with jQuery but I can't trigger it.
我用 jQuery 试过了,但我无法触发它。
Here is my React code that I tried but its not working:
这是我尝试过但不起作用的 React 代码:
var event = new Event('keypress', {
'keyCode' : 13,
'which' : 13,
'key' : 'Enter'
});
var node = document.getElementById('test23');
node.dispatchEvent(event);
回答by Matt Huggins
If you create a reference to the div, then you can trigger an event on it. With hooks, you can use useRef. Without hooks, you can use createRef.
如果创建对 div 的引用,则可以在其上触发事件。使用钩子,您可以使用useRef. 没有钩子,你可以使用createRef.
With hooks:
带钩子:
function MyComponent() {
const ref = useRef();
// This is simply an example that demonstrates
// how you can dispatch an event on the element.
useEffect(() => {
ref.dispatchEvent(new KeyboardEvent('keypress', {
key: 'Enter',
}));
}, []);
return (
<div
ref={ref}
id="test23"
contentEditable={true}
className="input"
placeholder="type a message"
data-reactid="137"
/>
);
}
Without hooks:
不带钩子:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
// This is simply an example that demonstrates
// how you can dispatch an event on the element.
triggerKeyPress() {
this.ref.dispatchEvent(new KeyboardEvent('keypress', {
key: 'Enter',
}));
}
render() {
return (
<div
ref={this.ref}
id="test23"
contentEditable={true}
className="input"
placeholder="type a message"
data-reactid="137"
/>
);
}
}
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
回答by Vishnu
If you're trying to create a keyboard event, you can make use of KeyboradEventconstructor.
如果您尝试创建键盘事件,则可以使用KeyboradEvent构造函数。
An enter key event can be dispatched like:
输入键事件可以像这样调度:
const event = new KeyboardEvent('keypress', {
key: 'enter',
});
console.log(event) // KeyboardEvent?{isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false,?…}
FYI: The react-keydownpackage is good for implementing keyboard navigation or other shortcuts.
仅供参考:react-keydown包非常适合实现键盘导航或其他快捷方式。

