如何覆盖Downshift默认生成的input ID?两种尝试均无效
Downshift 自定义Input ID 无效的解决方法
- 检查Downshift版本:低版本可能不支持
inputId参数,升级到最新稳定版后,再尝试通过getInputProps传入inputId参数。 - 使用
idPrefix全局配置:初始化Downshift组件时传入idPrefix属性,会自动为所有关联元素(包括input)添加前缀,示例代码:
<Downshift idPrefix="my-custom-prefix"> {({ getInputProps }) => ( <input {...getInputProps()} /> )} </Downshift>
此时input的id会变为my-custom-prefix-input。
- 手动覆盖并禁用Downshift的ID管理:如果上述方法无效,可以通过
getInputProps传入id,同时设置disableIdGeneration为true,彻底关闭Downshift的自动ID生成功能,示例:
<Downshift disableIdGeneration={true}> {({ getInputProps }) => ( <input {...getInputProps({ id: 'my-input-id' })} /> )} </Downshift>
也可以直接写死input的id,同时关闭自动生成:
<Downshift disableIdGeneration={true}> {() => ( <input id="my-input-id" /> )} </Downshift>
注意:关闭自动ID生成后,需要手动确保所有关联元素(如下拉菜单、标签等)的ID唯一性,避免影响无障碍访问体验。
内容的提问来源于stack exchange,提问作者Neha-Rajesh
相关产品推荐
相关产品推荐

