Reactjs 清除react中的材质UI文本字段值

Reactjs 清除react中的材质UI文本字段值,reactjs,material-ui,Reactjs,Material Ui,如何清除react中的materialUI文本字段值 检查以下代码- <TextField hintText="" ref={(node) => this._toField = node} onChange={this.changeToText} floatingLabelText="To*" floatingLabelFixed={true} fullWidth={true} /> this.\toField=node} onChange={this

如何清除react中的materialUI文本字段值

检查以下代码-

<TextField
  hintText=""
  ref={(node) => this._toField = node}
  onChange={this.changeToText}
  floatingLabelText="To*"
  floatingLabelFixed={true}
  fullWidth={true}
/>
this.\toField=node}
onChange={this.changeToText}
floatingLabelText=“To*”
floatingLabelFixed={true}
全宽={true}
/>

我正在使用raisedButton,同时按下它来验证上述字段。如果该字段有错误,则显示错误消息。如果没有,那么我们需要清除输入。但是我们如何才能清除输入文本呢?

您需要以某种方式存储输入的值。在这种情况下,国家似乎是一个初步的办法。无论文本何时更改,都必须更新状态。当您单击按钮并随后单击输入值时,同样适用:

类应用程序扩展了React.Component{
构造函数(){
超级()
此.state={
值:“”
}
this.handleChange=this.handleChange.bind(this)
this.handleClick=this.handleClick.bind(this)
}
手变(活动){
this.setState({value:event.target.value})
}
handleClick(){
//验证。。。
this.setState({value:''})
}
render(){
返回(
点击我
)
}
}
ReactDOM.render(
,
document.getElementById('root'))
)

有一个
属性必须传递给TextField组件。 检查下面的示例:

class SomeComponent extends Component {
  state = {value: ''}
  resetValue = () => {
    this.setState({value: ''});
  }
  render() {
    return (
      <div>
        <TextField
          ...
          value={this.state.value}
        />
        <button onClick={this.resetValue}>Reset</button>
      </div>
    )
  }
}
class SomeComponent扩展组件{
状态={值:“”
重置值=()=>{
this.setState({value:'});
}
render(){
返回(
重置
)
}
}

如果您使用的是无状态功能组件,则可以使用react钩子

还要确保您正在使用inputRef

import React, { useState, useRef } from "react";

let MyFunctional = props => {
  let textInput = useRef(null);

  return (
    <div>
      <Button
        onClick={() => {
          setTimeout(() => {
            textInput.current.value = "";
          }, 100);
        }}
      >
        Focus TextField
      </Button>
      <TextField
        fullWidth
        required
        inputRef={textInput}
        name="firstName"
        type="text"
        placeholder="Enter Your First Name"
        label="First Name"
      />
    </div>
  );
};
import React,{useState,useRef}来自“React”;
让MyFunctional=props=>{
设textInput=useRef(null);
返回(
{
设置超时(()=>{
textInput.current.value=“”;
}, 100);
}}
>
焦点文本字段
);
};

这是答案,OP使用的是ref,而不是inputRef