如何在React.js中触发按键事件

29

我是React.js的新手。 我正在尝试为文本框触发keypress事件。

这是文本框的代码,我想执行keypress触发器。

<div id="test23" contenteditable="true" class="input" placeholder="type a message" data-reactid="137">Hii...</div>

并且keypress方法是:

onKeyPress: function(e) {
   return "Enter" == e.key ? "Enter key event triggered" : void 0)
}

我尝试使用jQuery,但无法触发它。

这是我尝试过的React代码,但它不起作用:

var event = new Event('keypress', {
 'keyCode' : 13,
 'which' : 13,
 'key' : 'Enter'
});
var node = document.getElementById('test23');
node.dispatchEvent(event);
3个回答

3
如果你创建一个对div的引用,那么你可以在其上触发事件。使用hooks,你可以使用useRef。没有hooks,你可以使用createRef使用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"
    />
  );
}

没有钩子:

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'}));

'el' 未定义。 - ron_g
5
ref没有dispatchEvent方法。 - Andrea D_

0

如果您想创建一个键盘事件,可以使用KeyboradEvent构造函数。

可以像这样分派回车键事件:

const event = new KeyboardEvent('keypress', {
  key: 'enter',
});
console.log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …}

提醒一下:react-keydown 包非常适合实现键盘导航或其他快捷方式。


-4

测试工具 模拟 旨在在单元测试期间触发事件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接