How to trigger keypress event in React.js

前端 未结 3 2103
南旧
南旧 2020-12-30 21:34

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.

相关标签:
3条回答
  • 2020-12-30 22:17

    If you're trying to create a keyboard event, you can make use of KeyboradEvent constructor.

    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-keydown package is good for implementing keyboard navigation or other shortcuts.

    0 讨论(0)
  • 2020-12-30 22:18

    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.

    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'}));
    
    0 讨论(0)
  • 2020-12-30 22:22

    Test util Simulate is designed to trigger events during unit tests.

    0 讨论(0)
提交回复
热议问题