【问题标题】:Material ui textfield wont clear after state change状态更改后,材质 ui 文本字段不会清除
【发布时间】:2020-09-16 13:23:55
【问题描述】:

我有一个简单的文本字段,我想在按下按钮时清除它,由于某种原因无法正常工作。我将状态作为值传递给文本字段并更改状态,但该字段保持填充状态...

沙盒https://codesandbox.io/s/eager-edison-yqirl?file=/src/App.js

export default function App() {
  const [state, setState] = useState();
  const clear = () => {
    setState();
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <TextField value={state} id="outlined-basic" variant="outlined" />
      <button onClick={() => clear()}>clear</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:
    import React, { useState } from "react";
    import "./styles.css";
    import { TextField } from "@material-ui/core";
    export default function App() {
      const [state, setState] = useState("");
      const clear = () => {
        setState("");
      };
      const handleChange = (event) => {
        setState(event.target.value);
      };
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <TextField
            value={state}
            id="outlined-basic"
            variant="outlined"
            onChange={handleChange}
          />
          <button onClick={() => clear()}>clear</button>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2020-05-07
      • 1970-01-01
      • 2018-10-23
      • 2020-09-28
      • 2019-07-19
      相关资源
      最近更新 更多