如何在 React/JSX 中触发 onSelectStart?

How to fire onSelectStart in React/JSX?

我熟悉 HTML 中 selectstart 事件的用法。我在 JSX 中使用 onSelectStart。我希望它连接到 onselectstart。但是,它会发出一个警告,说它是未知的。

Warning: Unknown event handler property `onSelectStart`. It will be ignored.

示例代码:

function Example() {
  return (
    <div className="Example">
      <h2 onSelectStart={() => console.log("Selection started")}>Click</h2>
    </div>
  );
}

我已经用 react/react-dom@16.8.4react-scripts@3.0.1 试过了。

onSelectStart有替代品吗?如果是,如何实现?

显然 https://reactjs.org/docs/events.html#selection-events not supported by react it seems. Even on MDN docs this dont seem to be standardized event: https://developer.mozilla.org/en-US/docs/Web/API/Document/selectstart_event#Specifications 所以我会质疑其用法的有效性。

这是使用 refs 的解决方法:

https://codesandbox.io/s/fancy-wave-sotun

    ref={el => {
      el &&
        el.addEventListener("selectstart", () => {
          console.log("Selection started");
        });
    }}

只是不要忘记在卸载组件时删除事件侦听器。