简体   繁体   English

useRef 通过单击按钮重置 textInput

[英]useRef reset textInput by Clicking button

i am using material-ui for my project and i am doing function to reset text of input to empty when clicking an outer button, it seem like not worked out我正在为我的项目使用 material-ui 并且我正在执行在单击外部按钮时将输入文本重置为空的功能,这似乎没有解决

this is my code这是我的代码

var inputRef = useRef(null)

assign inputRef to the input field to access DOM将 inputRef 分配给输入字段以访问 DOM

<TextField label="Student Name" ref={inputRef} />

an outer button to reset text field to empty when click it:单击时将文本字段重置为空的外部按钮:

  <Button variant="contained" color="primary" onClick={() => {inputRef.current.value = ""}}>
    Reset
  </Button>

and it unchanged, if it is possible, please modify the code in the codesandbox link here , thank you so much并且它没有改变,如果可能,请在这里修改代码和框链接中的代码,非常感谢

You do incorrectly in step: assign inputRef to the input field to access DOM .您在步骤中做错了将 inputRef 分配给输入字段以访问 DOM It should be a ref of input element instead text field component (actual a div).它应该是input element的引用而不是text field component (实际上是一个 div)。

You should have state for value of Textfield Or using inputRef instead of ref to point to input element.您应该拥有 Textfield value的状态或使用inputRef而不是ref指向输入元素。 Demo 演示

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 can be used on html DOM elements( <input/> ). useRef 可用于 html DOM 元素( <input/> )。 To pass ref to Material-UI input you should use inputRef property.要将 ref 传递给 Material-UI 输入,您应该使用inputRef属性。

Please refer How can I use ref in TextField请参考如何在 TextField 中使用 ref

 var inputRef = useRef(null);

<TextField label="Student Name" inputRef={inputRef} />

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM