【问题标题】:Focus on Input when DIV is clicked单击 DIV 时关注输入
【发布时间】:2017-06-17 01:06:11
【问题描述】:

使用 React,当单击某些按钮/元素时,我试图将注意力集中在输入元素上。我需要能够在多次渲染后切换焦点。

例如,如果我单击一个名称按钮,名称输入框应该是焦点。如果我点击地址按钮,地址输入框应该是焦点。

我对使用 jQuery 进行此操作很熟悉,但使用 React.js 时它的行为似乎不如预期。

编辑:

我正在尝试使用按钮打开菜单。当菜单打开时,我希望焦点自动位于输入字段上。

我尝试了以下方法:

willFocus(name) {
  if(name==='nameButton') {
  oDocument.getElementById('nameInput').focus();
}
  • 使用标签/用于语义。 (不起作用,因为标签与输入的格式不同。)

【问题讨论】:

  • 你有没有尝试过?你有什么代码可以展示吗?
  • 请分享一些代码,简单的 HTML 显示您的输入。将帮助其余的。
  • 我正在寻找更多的灵感来源,但是,我尝试制作类似以下的函数willFocus(elementID) { if element id==="nameButton" { document.getElementById("nameInput").focus() }
  • 我相信语义上正确的方法是使用 label 元素。

标签: javascript jquery html css reactjs


【解决方案1】:

为您希望能够应用焦点的输入字段创建一个ref。我将其命名为textInput。我在这里使用了 es6 语法。

<input
  type="text"
  ref={node => {
     this.textInput = node 
  }
}/>

现在您已经引用了节点,现在可以从组件中的任何位置访问输入元素。

在这个输入元素中应用焦点,就像this.textInput.focus()一样简单

创建一个函数,将焦点方法应用于被引用的节点。

 handleMenuClick() {
   this.textInput.focus()
 }

现在你可以在有人点击菜单按钮时调用这个函数

<div 
 onClick={this.handleMenuClick.bind(this)}
> I AM MENU TITLE </div>

【讨论】:

    【解决方案2】:

    您可以使用The ref Callback Attribute。以输入为例:

    render() {
      // Use the `ref` callback to store a reference to the text input DOM
      // element in this.textInput.
      return (
        <div>
          <input
            type="text"
            ref={(input) => { this.textInput = input }}
          />
          ...
        </div>
      )
    }
    

    然后,您可以通过以下方式明确关注输入:

    this.textInput.focus();
    

    【讨论】:

      【解决方案3】:

      一种非常简单的方法是使用&lt;label&gt; 元素:

      <div>
      <label for='input1'>Click here</label>
      <input type='text' id='input1' />
      </div>
      <div>
      <label for='input2'>Click here</label>
      <input type='text' id='input2' />
      </div>
      <div>
      <label for='input3'>Click here</label>
      <input type='text' id='input3' />
      </div>
      

      工作示例:https://jsfiddle.net/kq3okzas/

      【讨论】:

        【解决方案4】:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-10
          • 2018-05-18
          • 1970-01-01
          • 2019-11-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多