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

How to apply useRef() in React TS?

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

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

"Uncaught Error: Function components cannot have string refs. We recommend using useRef() instead"

如何在这种情况下应用 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;

您可以使用 useRef 创建一个 ref,然后使用大括号将该 ref 传递给 HTML,就像这样

function App() {
  var mytext = useRef(null); // Create ref with no initial value
  function test() {
    var name = mytext?.current?.value; // Get ref value

    console.log(name);
  }

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

在功能组件中你必须使用 ref={mytext} 而不是 ref="mytext"

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


function App() {

  const mytext = useRef<any>(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;

您也可以使用 useRef(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;