ReactJS 和自动对焦

2023-11-27

我有一个react-bootstrap模态与<input>。我想设置自动对焦属性<input>

下列工作正常,但在控制台中显示警告

<input type="text" autofocus='true' />
Warning: Invalid DOM property `autofocus`. Did you mean `autoFocus`?

以下选项不工作,从某种意义上说,它们在打开模式时不会聚焦输入:

<input type="text" autoFocus='true' />
<input type="text" autoFocus={true} />
<input type="text" autoFocus />

设置自动对焦的推荐方法是什么?或者我应该如何消除效果良好的示例的警告?

注意:这是react 16.8.6


如果您使用 React Hooks,请添加useCallback()到您的组件并添加ref={callback}到表单控件:

import React, { useCallback } from 'react'

function InputComponent() {
    const autoFocus = useCallback(el => el ? el.focus() : null, [])

    return <input type="text" ref={autoFocus} />
}

export default InputComponent

您可以更换<input>使用 React BootstrapFormControl too.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ReactJS 和自动对焦 的相关文章

随机推荐