清除反应中的材质 UI 文本字段值

Shu*_*ham 6 reactjs material-ui

如何清除反应中的 materialUI 文本字段值?

检查以下代码 -

<TextField
  hintText=""
  ref={(node) => this._toField = node}
  onChange={this.changeToText}
  floatingLabelText="To*"
  floatingLabelFixed={true}
  fullWidth={true}
/>
Run Code Online (Sandbox Code Playgroud)

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

44k*_*rma 7

如果您使用的是无状态功能组件,那么您可以使用 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>
  );
};
Run Code Online (Sandbox Code Playgroud)


mer*_*lin -1

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

class App extends React.Component {
  constructor() {
    super()

    this.state = {
      value: ''
    }

    this.handleChange = this.handleChange.bind(this)
    this.handleClick = this.handleClick.bind(this)
  }
  
  handleChange(event) {
    this.setState({ value: event.target.value })
  }

  handleClick() {
    // validation...
    this.setState({ value: '' })
  }

  render() {
    return (
      <div>
        <input type="text" value={this.state.value} onChange={this.handleChange}/>
        <button onClick={this.handleClick}>Click-me</button>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)