How to use refs in React with Typescript

前端 未结 15 1464
闹比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条回答
  •  长情又很酷
    2020-11-28 05:17

    From React type definition

        type ReactInstance = Component | Element;
    ....
        refs: {
                [key: string]: ReactInstance
        };
    

    So you can access you refs element as follow

    stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);
    

    without redefinition of refs index.

    As @manakor mentioned you can get error like

    Property 'stepInput' does not exist on type '{ [key: string]: Component | Element; }

    if you redefine refs(depends on IDE and ts version you use)

提交回复
热议问题