![](/img/trans.png)
[英]How to use useRef hook to select next TextInput after pressing next keyboard button with redux-form
[英]useRef reset textInput by Clicking button
我正在為我的項目使用 material-ui 並且我正在執行在單擊外部按鈕時將輸入文本重置為空的功能,這似乎沒有解決
這是我的代碼
var inputRef = useRef(null)
將 inputRef 分配給輸入字段以訪問 DOM
<TextField label="Student Name" ref={inputRef} />
單擊時將文本字段重置為空的外部按鈕:
<Button variant="contained" color="primary" onClick={() => {inputRef.current.value = ""}}>
Reset
</Button>
並且它沒有改變,如果可能,請在這里修改代碼和框鏈接中的代碼,非常感謝
您在步驟中做錯了:將 inputRef 分配給輸入字段以訪問 DOM 。 它應該是input element
的引用而不是text field component
(實際上是一個 div)。
您應該擁有 Textfield value
的狀態或使用inputRef
而不是ref
指向輸入元素。 演示
import React, { useRef } from "react";
import { TextField, Button } from "@material-ui/core";
import "./styles.css";
export default function App() {
var inputRef = useRef(null);
return (
<div className="App">
<TextField label="Student Name" inputRef={inputRef} />
<Button
onClick={() => {
console.log(inputRef);
inputRef.current.value = "";
}}
variant="contained"
color="primary"
>
Reset
</Button>
</div>
);
}
useRef 可用於 html DOM 元素( <input/>
)。 要將 ref 傳遞給 Material-UI 輸入,您應該使用inputRef屬性。
var inputRef = useRef(null);
<TextField label="Student Name" inputRef={inputRef} />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.