typescript - Hur man använder useRef() i React TS?
Mål:
Hämta värdet från textrutan när du klickar på knappen
Problem:
Värdet visas inte i konsolen.
"Uncaught Error: Function components cannot have string refs. We recommend using useRef() instead"
Hur använder man useRef() i detta sammanhang?
Stackblitz
https://stackblitz.com/edit/react-ts-mcn4jd?file=index.tsx
Info:
*Nybörjare i react TS
Tack!
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;
Svar #1
Du kan också använda useRef<HTMLInputElement | null>(null) för bättre typsupport
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;
Svar #2
Du kan använda useRef för att skapa en ref, och sedan skicka den referensen till HTML med måsvingar, på detta sätt
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>
);
}
