How to focus a input field, which is located in a child component

删除回忆录丶 提交于 2019-12-04 20:02:59

问题


I have a button in a parent component. I want to focus an input field, which is located in a child component, by clicking on that button. How can I do it.


回答1:


You can make use of refs to achieve the result

class Parent extends React.Component {
  
  handleClick = () => {
    this.refs.child.refs.myInput.focus();
  }
  render() {
    return (
      <div>
        <Child ref="child"/>
        <button onClick={this.handleClick.bind(this)}>focus</button>
      </div>
    )
  }
}

class Child extends React.Component {
  render() {
    return (
      <input type="text" ref="myInput"/>
    )
  }
}

ReactDOM.render(<Parent/>, 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>

UPDATE:

React docs recommend on using a ref callback rather than string refs

class Parent extends React.Component {
  
  handleClick = () => {
    this.child.myInput.focus();
  }
  render() {
    return (
      <div>
        <Child ref={(ch) => this.child = ch}/>
        <button onClick={this.handleClick.bind(this)}>focus</button>
      </div>
    )
  }
}

class Child extends React.Component {
  render() {
    return (
      <input type="text" ref={(ip)=> this.myInput= ip}/>
    )
  }
}

ReactDOM.render(<Parent/>, 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>



回答2:


You can simply use componentDidMount() in your child component as in below

class Child extends React.Component {
  componentDidMount() {
   this.myInput.focus()
  }

  render() {
    return (
      <input type="text" ref={(input)=> this.myInput= input}/>
    )
  }
}



回答3:


Instead of accessing the child component's input element from parent, it's better to expose a method as below,

class Parent extends React.Component {

  handleClick = () => {
    this.refs.child.setFocus();
  };

  render() {
    return (
      <div>
        <Child ref="child"/>
        <button onClick={this.handleClick.bind(this)}>focus</button>
      </div>
    )
  }
}

class Child extends React.Component {

  setFocus() {
    this.refs.myInput.focus();
  }

  render() {
    return (
      <input type="text" ref="myInput"/>
    )
  }
}

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


来源:https://stackoverflow.com/questions/42017401/how-to-focus-a-input-field-which-is-located-in-a-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!