我有一个简单的文本字段,由于某种原因,我想在按下按钮时清除该文本字段。.我将状态作为值传递给文本字段并更改状态,但该字段保持填充状态... < / p>
沙盒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>
);
}
答案 0 :(得分: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>
);
}