点击< div>重点<输入> (反应) [英] Click on <div> to focus <input> (React)

查看:95
本文介绍了点击< div>重点<输入> (反应)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何用jQuery来做到这一点。但我坚持使用React:每当用户点击一个div时,如何关注输入字段?

您需要在div上调用 onClick 事件,并调用您可以访问的input元素上的 focus()函数 refs in react

  class App extends React.Component {render(){return(< div>< div onClick = {()=> {this.myInp.focus()}}>焦点输入< / div>< (< / app>,document.getElementById('app'));其中, ));  

 < script src =https:/ /cdnjs.cloudflare.com/ajax/libs/react/15.1.0/r eact.min.js>< / script>< script src =https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js>< ; / script>< div id =app>< / div>  

b $ b

在上面的代码片段 ref = {(ip)=> this.myInp = ip} 是一个声明refs的回调方法,由 react-docs


I know how to do this with jquery. But I am stuck with React: How would I focus an input field, whenever the user clicks on a div?

解决方案

You need to have an onClick event on the div and the call the focus() function on the input element that you can access by refs in react

class App extends React.Component {
  
  render() {
    return (
      <div>
          <div onClick={() => {this.myInp.focus()}}>Focus Input</div>
          <input type="text" ref={(ip) => this.myInp = ip} />
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

In the above snippet ref={(ip) => this.myInp = ip} is a callback approach of declaring refs which is recommended by react-docs

这篇关于点击&lt; div&gt;重点&lt;输入&gt; (反应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆