How to use refs in React with Typescript

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

    React.createRef (class components)

    class ClassApp extends React.Component {
      inputRef = React.createRef();
      
      render() {
        return 
      }
    }
    

    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(null) // note the passed in `null` arg
      return 
    }
    
    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(null)
    

    Callback refs (work for both)

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

    Playground sample

提交回复
热议问题