How to use refs in React with Typescript

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

    For typescript user no constructor required.

    ...

    private divRef: HTMLDivElement | null = null
    
    getDivRef = (ref: HTMLDivElement | null): void => {
        this.divRef = ref
    }
    
    render() {
        return <div ref={this.getDivRef} />
    }
    

    ...

    0 讨论(0)
  • 2020-11-28 05:34

    React.createRef (class components)

    class ClassApp extends React.Component {
      inputRef = React.createRef<HTMLInputElement>();
      
      render() {
        return <input type="text" ref={this.inputRef} />
      }
    }
    

    Note: Omitting the old String Refs legacy API here...


    React.useRef (Hooks / function components)

    Readonly refs for DOM nodes:
    const FunctionApp = () => {
      const inputRef = React.useRef<HTMLInputElement>(null) // note the passed in `null` arg
      return <input type="text" ref={inputRef} />
    }
    
    Mutable refs for arbitrary stored values:
    const FunctionApp = () => {
      const renderCountRef = useRef(0)
      useEffect(() => {
        renderCountRef.current += 1
      })
      // ... other render code
    }
    

    Note: Don't initialize useRef with null in this case. It would make the renderCountRef type readonly (see example). If you need to provide null as initial value, do this:

    const renderCountRef = useRef<number | null>(null)
    

    Callback refs (work for both)

    // Function component example 
    const FunctionApp = () => {
      const handleDomNodeChange = (domNode: HTMLInputElement | null) => {
        // ... do something with changed dom node.
      }
      return <input type="text" ref={handleDomNodeChange} />
    }
    

    Playground sample

    0 讨论(0)
  • 2020-11-28 05:34

    Just to add a different approach - you can simply cast your ref, something like:

    let myInputElement: Element = this.refs["myInput"] as Element
    
    0 讨论(0)
提交回复
热议问题