javascript - 在 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>
);
};
正如您在代码中看到的那样,我尝试使用我发现的两种不同方法来做到这一点:
通过
useRef()
:这什么都不做,没有错误或任何东西,但不会模糊我的元素通过
document.activeElement
: 这给了我一个错误,显然blur
类型元素上不存在属性。
选择选项时模糊我的 Select 组件的正确方法是什么?
解决方案
将一些评论总结为答案:
正如@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
.
推荐阅读
- c# - .NET Core 上的 WCF 在授权方案中缺少客户端协商方案
- javascript - React Native - 为什么当我将 textInput 分配给 onchange 时单击按钮时才会出现错误?
- kubernetes - 如何在 GCP 集群上安装 Kubernetes v1.10.11?
- javascript - Vue.js 组件不会呈现
- android - 从实时数据库中取出数据
- javascript - Javascript lodash - 基于属性值的数据按摩
- javascript - 如何忽略缺失的参数
- javascript - 如何将跟踪器添加到磁力链接?
- postgresql - Postgres 10.3:SELECT 查询挂了几个小时
- java - 从 App Engine 应用程序将文件上传到 Google Drive