【问题标题】:React + modal: input field auto focusReact + modal:输入字段自动对焦
【发布时间】:2018-02-28 13:17:09
【问题描述】:

我正在使用ReactAnt Design

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

问题

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

我尝试使用 HTML5 autoFocus

<textarea autoFocus></textarea>

但它不起作用,这里的代码:stackblitz

【问题讨论】:

标签: reactjs autofocus


【解决方案1】:

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

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

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

链接到Modal API https://react-bootstrap.github.io/components/modal/#modal-props

【讨论】:

【解决方案2】:

当你显示Modal时,你可以使用textarea中的ref来手动设置焦点。

 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

【讨论】:

  • 感谢@Dev。当有两个弹出按钮时,它不起作用。同时显示两个弹出按钮
  • 您将拥有多少个 Popover?如果您要重用它们,我建议通过适当设置状态来更改弹出框的可见性。让我更新答案
  • @MariaJeysinghAnbu,更新了答案。希望这会有所帮助
  • 它对我有用,但我不明白其中的逻辑。您是否有指向此 ref 属性和 setState 的第二个参数的文档的链接?
  • 它对我不起作用。只是浪费时间。 console.log(this.testInput); // 未定义
【解决方案3】:

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

<Modal ... autoFocus={false}>

<textarea autoFocus={true}>

【讨论】:

  • 打开一个模态后,我正在模态中加载一个tinymce编辑器。当在引导模式顶部打开任何 tinymce 模式时,没有一个 tinymce 模式输入控件被聚焦。尝试在 Modal 上将 autoFocus 设置为 false,但仍然没有用。任何其他解决方案
  • 这就像一个魅力,你能指定在反应中使用autofocus 属性与使用useRef 有什么区别吗?因为要使 useRef 在像 React Modal 这样的动态渲染组件中工作,它需要一些工作,而不是使用自动对焦它可以轻松实现所需的结果,提前致谢
【解决方案4】:

只需在模态上添加 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2018-08-17
    • 2011-10-12
    • 2014-06-04
    • 2013-06-20
    相关资源
    最近更新 更多