如何在React.js中触发keypress事件

Piy*_*ush 17 javascript jquery javascript-events reactjs

我是React.js的新手.我正在尝试触发文本div的按键事件.

这里是我要执行按键触发器的文本框代码.

<div id="test23" contenteditable="true" class="input" placeholder="type a message" data-reactid="137">Hii...</div>
Run Code Online (Sandbox Code Playgroud)

和按键方法是

onKeyPress: function(e) {
   return "Enter" == e.key ? "Enter key event triggered" : void 0)
}
Run Code Online (Sandbox Code Playgroud)

我用jquery尝试了但是我无法触发它.

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

var event = new Event('keypress', {
 'keyCode' : 13,
 'which' : 13,
 'key' : 'Enter'
});
var node = document.getElementById('test23');
node.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Mat*_*ins 5

如果创建对 div 的引用,则可以在其上触发事件。使用钩子,您可以使用useRef. 没有钩子,你可以使用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"
    />
  );
}
Run Code Online (Sandbox Code Playgroud)

不带钩子:

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'}));
Run Code Online (Sandbox Code Playgroud)

  • ref 没有方法dispatchEvent (5认同)

Val*_*éry -4

Test util Simulate旨在在单元测试期间触发事件。