反应|模态输入字段自动对焦

时间:2018-02-28 13:17:10

标签: reactjs autofocus

我使用Reactant design作为我的项目。

我有一个Popover,它有一个按钮。当用户单击按钮时它显示带有输入字段

的模态

问题

当我单击“显示模态按钮”时,自动对焦不起作用且弹出窗口也未隐藏

我尝试使用HTML5 autoFocus

<textarea autoFocus></textarea>

但它没有用。我在stackblitz

上有完整的代码

3 个答案:

答案 0 :(得分:2)

向您的模式中添加 autoFocus = {false} 以拒绝该模式的焦点管理。

<Modal ... autoFocus={false}>

<textarea autoFocus={true}>

答案 1 :(得分:0)

当您展示模态时,您可以使用ref的{​​{1}}手动设置焦点。

textarea

在你的模态中,

 showModal=()=> {
    this.setState({
        visible: true,
        popOverVisible: false
    },()=>{
      setTimeout(()=>{this.testInput && this.testInput.focus()}, 1);
    });
 }

要隐藏Popover,您可以使用<Modal ...> ... <textarea type='text' ref={(textarea) => { this.testInput = textarea; }} ></textarea> ... </Modal> 的{​​{1}}道具并相应地设置状态。

visible

希望这有帮助。

Working demo

对于多个PopOvers:Demo

答案 2 :(得分:0)

对我有用的是在模式完成转换后设置输入的焦点。

使用useRef钩子,我的代码就像

...
<Modal ... onEntered={() => textarea.current.focus()} >
    <textarea  ... ref={textarea} />
</Modal>

链接到Modal API https://react-bootstrap.netlify.com/components/modal/#modals-props

相关问题