当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Focus on Input when DIV is clicked

问题描述:

Using React, I am trying to focus on an input element when certain buttons/elements are clicked. I need the ability to switch focus after render multiple times.

For example, If I click a name button, the name input box should focus. If I click the address button, the address input box should focus.

I'm familiar doing this with jQuery but it does not seem to behave as expected with React.js.

EDIT:

I am trying to use a button to open a menu. When the menu opens, I want the focus to automatically be on an input field.

I've tried the following:

willFocus(name) {

if(name==='nameButton') {

oDocument.getElementById('nameInput').focus();

}

  • Using the label/for semantic. (Doesn't work because the label is not in the same form as the input.)

网友答案:

Use label. No javascript necessary.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

网友答案:

One very simple way is to use a <label> element:

<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>

Working example: https://jsfiddle.net/kq3okzas/

网友答案:

You could use The ref Callback Attribute. Taking an example of an input:

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>
  )
}

Then, you are able to explicitly focus the input by:

this.textInput.focus();
网友答案:

Create a ref to the input field you want to be able to apply focus. I've named it textInput. I've used es6 syntax here.

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

Now you have reference to the node and can now access the input element from anywhere in the component.

To apply the focus in this input element, is as simple as this.textInput.focus()

Create a function that will apply the focus method to the node being referenced.

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

Now you can call this function when someone clicks the menu button for example

<div 
 onClick={this.handleMenuClick.bind(this)}
> I AM MENU TITLE </div>
分享给朋友:
您可能感兴趣的文章:
随机阅读: