how react programmatically focus input

前端 未结 6 2101
滥情空心
滥情空心 2020-12-15 03:01

I\'m trying to implement a very simple use case, a UI feature, where:

  1. There is a label with some content in it
  2. If clicked, a text input replaces it wi
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 03:30

    The way you have used refs is not the most preferred way or else its not the best practice anymore . try some thing like this

    class MyClass extends React.Component {
      constructor(props) {
        super(props);
        this.focus = this.focus.bind(this);
      }
    
      focus() {
        this.textInput.current.focus();
      }
    
      render() {
    
        return (
          
    { this.textInput = input; }} />
    ); } }

    Update
    From React 16.3 upwards you can use the React.createRef() API

    class MyClass extends React.Component {
      constructor(props) {
        super(props);
        // create a ref to store the textInput DOM element
        this.textInput = React.createRef();
        this.focus = this.focus.bind(this);
      }
    
      focus() {
        // Explicitly focus the text input using the raw DOM API
        // Note: we're accessing "current" to get the DOM node
        this.textInput.current.focus();
      }
    
      render() {
        // tell React that we want to associate the  ref
        // with the `textInput` that we created in the constructor
        return (
          
    ); } }

提交回复
热议问题