React + modal:输入字段自动对焦

React + modal: input field auto focus

我正在使用 ReactAnt Design

我有一个带按钮的弹出窗口。当用户单击按钮时,它会显示带有输入字段的模式。

问题

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

我试过 HTML5 autoFocus

<textarea autoFocus></textarea>

但是没有用,这里是代码:stackblitz

显示模态框时,您可以使用 textarearef 手动设置焦点。

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

在你的模式中,

<Modal ...>
  ...
  <textarea 
   type='text'
   ref={(textarea) => { this.testInput = textarea; }} ></textarea>
  ...
</Modal>

要隐藏 Popover,您可以使用 PopOvervisible 属性并相应地设置状态。

 showPopOver = () => {
    this.setState({
      popOverVisible: true
    })
 }
 ...
 <Popover ...
   visible={this.state.popOverVisible}>
   <span type="primary" onClick={this.showPopOver}>Click me (Popover Button)</span>
 </Popover>

希望这对您有所帮助。

Working demo

对于多个 PopOver:Demo

autoFocus={false} 添加到您的模态框以拒绝模态框的焦点管理。

<Modal ... autoFocus={false}>

<textarea autoFocus={true}>

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

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

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

Link 至 Modal API https://react-bootstrap.github.io/components/modal/#modal-props

只需在模式上添加 autoFocus = {false} 并在输入上添加 autoFocus = {true}。

<Modal autoFocus={false}>
  <Form>
    <ModalHeader>Type Your Input</ModalHeader>
    <ModalBody>
      <Input autoFocus={true} />
      <Button>Submit</Button>
    </ModalBody>
  </Form>
</Modal>

参考:https://simplernerd.com/js-reactstrap-modal-autofocus/