How to use refs in React with Typescript

前端 未结 15 1470
闹比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:14

    To use the callback style (https://facebook.github.io/react/docs/refs-and-the-dom.html) as recommended on React's documentation you can add a definition for a property on the class:

    export class Foo extends React.Component<{}, {}> {
    // You don't need to use 'references' as the name
    references: {
        // If you are using other components be more specific than HTMLInputElement
        myRef: HTMLInputElement;
    } = {
        myRef: null
    }
    ...
     myFunction() {
        // Use like this
        this.references.myRef.focus();
    }
    ...
    render() {
        return( { this.references.myRef = i; }}/>)
    }
    

提交回复
热议问题