首页 > 解决方案 > 在 onChange 事件上模糊材质 UI 选择组件

问题描述

默认情况下,MaterialUI 的 Select 组件在选择一个选项后会保持焦点。这种行为可以在他们文档中的所有示例中看到

一旦选择了某些东西,我希望元素模糊。这是我的代码目前的样子:

const App = () => {
    const [selectedValue, setSelectedValue] = useState('')

    const selectElement = useRef(null);

  return (
        <Select
            native
            ref={selectElement}
            value={selectedValue}
            onChange={(evt) => {
                setSelectedValue(evt.target.value)

                // Attempt at blurring the element upon selection using the useRef:
                selectElement.current.blur(); // Nothing happens

                // Attempt at blurring the element upon selection using activeElement:
                document.activeElement.blur(); // Get Error: "Property 'blur' does not exist on type 'Element'."
            }}
        >
            <option value='option 1'>Option 1</option>
            <option value='option 2'>Option 2</option>
            <option value='option 3'>Option 3</option>
        </Select>
  );
};

正如您在代码中看到的那样,我尝试使用我发现的两种不同方法来做到这一点:

选择选项时模糊我的 Select 组件的正确方法是什么?

标签: javascriptreactjsmaterial-uidom-events

解决方案


将一些评论总结为答案:

正如@2pha 建议的那样,使用evt.target.blur()可能是要走的路:

const App = () => {
  const [selectedValue, setSelectedValue] = useState('');

  return (
    <Select
      native
      value={selectedValue}
      onChange={(evt) => {
        setSelectedValue(evt.target.value);

        console.log(document.activeElement); // <select>
        evt.target.blur();
        console.log(document.activeElement); // <body>
      }}>
      <option value="option 1">Option 1</option>
      <option value="option 2">Option 2</option>
      <option value="option 3">Option 3</option>
    </Select>
  );
};

沙盒:https ://codesandbox.io/s/empty-night-oqlgr

ref 不起作用,因为它被转发到根元素(a div) 而不是select元素。

您看到的错误document.activeElement看起来与 TypeScript 相关。您看到它是因为document.activeElement它的一般类型为Element,它没有blur方法。您需要指定HTMLSelectElement类型,但似乎不值得追求这条路线,因为它更直接使用evt.target.


推荐阅读