How to use refs in React with Typescript

前端 未结 15 1436
闹比i
闹比i 2020-11-28 05:03

I\'m using Typescript with React. I\'m having trouble understanding how to use refs so as to get static typing and intellisense with respect to the react nodes referenced by

15条回答
  •  -上瘾入骨i
    2020-11-28 05:13

    Since React 16.3 the way to add refs is to use React.createRef as Jeff Bowen pointed in his answer. However you can take advantage of Typescript to better type your ref.

    In your example you're using ref on input element. So they way I would do it is:

    class SomeComponent extends React.Component {
        private inputRef: React.RefObject;
        constructor() {
            ...
            this.inputRef = React.createRef();
        }
    
        ...
    
        render() {
            ;
        }
    }
    

    By doing this when you want to make use of that ref you have access to all input methods:

    someMethod() {
        this.inputRef.current.focus(); // 'current' is input node, autocompletion, yay!
    }
    

    You can use it on custom components as well:

    private componentRef: React.RefObject>;
    

    and then have, for example, access to props :

    this.componentRef.current.props; // 'props' satisfy IProps interface
    

提交回复
热议问题