如何在React TS中应用useRef()?

Wha*_*sUP 4 typescript react-tsx react-hooks

目标:
单击按钮时从文本框中获取值

问题:
该值不显示在控制台中。

"Uncaught Error: Function components cannot have string refs. We recommend using useRef() instead"
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何应用 useRef() ?

Stackblitz
https://stackblitz.com/edit/react-ts-mcn4jd?file=index.tsx

信息:
*React TS 新手

谢谢你!

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  function test() {
    // Get the value and display it at consol
    //var name = refs.mytext.value;
    
    var element = document.getElementById("ddddd");


    console.log(element);
  }

  return (
    <div className="App">
      <input type="text" id="ddddd" ref="mytext" />
      <button onClick={() => test()}>Add</button>
    </div>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

小智 5

您还可以使用 useRef<HTMLInputElement | null>(null) 以获得更好的类型支持

import React, {useRef} from 'react';
import logo from './logo.svg';
import './App.css';


function App() {

  const mytext = useRef<HTMLInputElement | null>(null);

  function test() {
    // Get the value and display it at consol
    //var name = refs.mytext.value;
    
    var element = document.getElementById("ddddd");


    console.log(mytext.current?.value);
  }

  return (
    <div className="App">
      <input type="text" id="ddddd" ref={mytext} />
      <button onClick={() => test()}>Add</button>
    </div>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)