【问题标题】:How to trigger keypress event in React.js如何在 React.js 中触发按键事件
【发布时间】:2015-03-22 01:40:12
【问题描述】:

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

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

<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 尝试过,但我无法触发它。

这是我尝试过但无法正常工作的 React 代码:

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

【问题讨论】:

    标签: javascript jquery reactjs dom-events


    【解决方案1】:

    如果您创建对 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"
        />
      );
    }
    

    没有钩子:

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

    【讨论】:

      【解决方案2】:

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

      回车键事件可以像这样发送:

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

      仅供参考:react-keydown 包非常适合实现键盘导航或其他快捷方式。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多