你不知道的React系列(四十六)合成事件

73 阅读1分钟

概览

  • 使用浏览器的底层事件,使用 nativeEvent 属性来获取

  • 合成事件与浏览器的原生事件不同,不会直接映射到原生事件

    onMouseLeave 事件中 event.nativeEvent 将指向 mouseout 事件

  • 事件处理器返回 false 时,不再阻止事件传递

    手动调用 e.stopPropagation() 或 e.preventDefault()

  • 使用捕获阶段的事件处理函数,则应为事件名添加 Capture

    onClickCapture

事件

  • 焦点事件

    onFocus onBlur

    这些焦点事件在 React DOM 上的所有元素都有效,不只是表单元素。

  • 监听焦点的进入与离开

    使用 currentTarget 和 relatedTarget 来区分聚焦和失去焦点是否来自父元素外部

    function Example() {
      return (
        <div
          tabIndex={1}
          onFocus={(e) => {
            if (e.currentTarget === e.target) {
              console.log('focused self');
            } else {
              console.log('focused child', e.target);
            }
            if (!e.currentTarget.contains(e.relatedTarget)) {
              // Not triggered when swapping focus between children
              console.log('focus entered self');
            }
          }}
          onBlur={(e) => {
            if (e.currentTarget === e.target) {
              console.log('unfocused self');
            } else {
              console.log('unfocused child', e.target);
            }
            if (!e.currentTarget.contains(e.relatedTarget)) {
              // Not triggered when swapping focus between children
              console.log('focus left self');
            }
          }}
        >
          <input id="1" />
          <input id="2" />
        </div>
      );
    }
    
  • onScroll 事件在 React 中不再冒泡

  • currentTarget、type React 事件对象可能和原生 Event 对象不一样