如何在React.js中触发按键事件 [英] How to trigger keypress event in React.js
本文介绍了如何在React.js中触发按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是React.js的新手. 我正在尝试触发文本div的按键事件.
I'm new to React.js. I'm trying to trigger keypress event for text 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>
和按键方法是:
onKeyPress: function(e) {
return "Enter" == e.key ? "Enter key event triggered" : void 0)
}
我用jQuery尝试过,但无法触发它.
I tried it with jQuery but I can't trigger it.
这是我尝试过的我的React代码,但是它不起作用:
Here is my React code that I tried but its not working:
var event = new Event('keypress', {
'keyCode' : 13,
'which' : 13,
'key' : 'Enter'
});
var node = document.getElementById('test23');
node.dispatchEvent(event);
推荐答案
如果创建对div的引用,则可以在其上触发事件.使用挂钩,您可以使用 useRef
.如果没有钩子,则可以使用 createRef
.
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
.
带钩子:
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"
/>
);
}
不带钩子:
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'}));
这篇关于如何在React.js中触发按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文