如何使用JavaScript禁用iPad、iPhone键盘上方的预测建议输入栏
解决方案
你当前配置不生效主要有两个可修复的问题:一是autoCapitalize属性传值错误,该属性的合法关闭值为off,而非字符串false;二是属性分散在组件根节点和inputProps中,可能出现MUI透传冲突,同时iOS需要额外的专属属性关闭预测栏,可按以下步骤修改:
- 统一把所有控制属性放到
inputProps中,修正传值错误,新增iOS专属的disablePredictiveText属性,修正后的代码如下:
<InputBase classes={{ root: classes.inputRoot, input: classes.input, }} type="text" autoFocus value={title} inputProps={{ maxLength: 50, spellCheck: false, 'data-gramm': false, autoCapitalize: 'off', autoCorrect: 'off', autoComplete: 'off', disablePredictiveText: true }} onChange={(event: React.ChangeEvent<HTMLInputElement>) => setTitle(event.target.value)} />
- 如果以上配置仍不生效,可以把
type属性改为search,iOS系统对搜索类输入框默认会关闭预测建议栏,键盘布局和普通文本输入完全一致,不会影响用户输入体验。 - 极端场景下可以通过ref强制修改原生input属性,避免框架渲染逻辑覆盖你的自定义配置:
import { useRef } from 'react'; const inputRef = useRef<HTMLInputElement>(null); <InputBase classes={{ root: classes.inputRoot, input: classes.input, }} type="text" autoFocus value={title} inputRef={inputRef} onFocus={() => { if (inputRef.current) { inputRef.current.setAttribute('autocorrect', 'off'); inputRef.current.setAttribute('spellcheck', 'false'); inputRef.current.setAttribute('autocapitalize', 'off'); inputRef.current.setAttribute('disablepredictivetext', 'true'); } }} inputProps={{ maxLength: 50, spellCheck: false, 'data-gramm': false, autoCapitalize: 'off', autoCorrect: 'off', autoComplete: 'off', disablePredictiveText: true }} onChange={(event: React.ChangeEvent<HTMLInputElement>) => setTitle(event.target.value)} />
内容的提问来源于stack exchange,提问作者Nitish Kalra
相关产品推荐
相关产品推荐

