如何实现点击按钮清除MUI Autocomplete选中值及UI数据?
问题:清除MUI Autocomplete选中值及绑定的state数据
我想要创建一个按钮,点击后同时清除MUI Autocomplete的选中值,以及UI上展示的data数据。目前点击按钮只能清空UI上的data,但Autocomplete组件通过onChange绑定的选中值还保留着,需要实现点击「Clear Data & Autocomplete」按钮时一并清除这个值。
点击按钮前:
点击按钮后:
如图所示,点击按钮后Autocomplete的选中状态仍未清除,需要解决这个问题。
原代码:
import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; export default function ComboBox() { const [data, setData] = React.useState(""); return ( <> <Autocomplete disablePortal id="combo-box-demo" options={top100Films.map((movie) => movie.label)} onChange={(e, val) => setData(val)} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Movie" />} /> <h1>{data}</h1> <button onClick={() => setData("")}>Clear Data & Autocomplete</button> </> ); } const top100Films = [ { label: "The Shawshank Redemption", year: 1994 }, { label: "The Godfather", year: 1972 }, { label: "The Godfather: Part II", year: 1974 }, { label: "The Dark Knight", year: 2008 }, { label: "12 Angry Men", year: 1957 }, { label: "Schindler's List", year: 1993 }, { label: "Pulp Fiction", year: 1994 } ];
解决方案
要同时清除Autocomplete的选中状态和绑定的data,需要给Autocomplete组件添加value属性绑定data,并且在清空时将data设为null(而非空字符串),因为MUI的Autocomplete组件需要用null表示未选中状态。
修改后的代码:
import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; export default function ComboBox() { const [data, setData] = React.useState(null); // 初始值设为null return ( <> <Autocomplete disablePortal id="combo-box-demo" options={top100Films.map((movie) => movie.label)} value={data} // 添加value绑定,实现组件与state双向同步 onChange={(e, val) => setData(val)} sx={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Movie" />} /> <h1>{data || ""}</h1> {/* 处理null状态,避免页面显示"null" */} <button onClick={() => setData(null)}>Clear Data & Autocomplete</button> {/* 清空时设为null */} </> ); } const top100Films = [ { label: "The Shawshank Redemption", year: 1994 }, { label: "The Godfather", year: 1972 }, { label: "The Godfather: Part II", year: 1974 }, { label: "The Dark Knight", year: 2008 }, { label: "12 Angry Men", year: 1957 }, { label: "Schindler's List", year: 1993 }, { label: "Pulp Fiction", year: 1994 } ];
关键修改点:
- 将
data初始状态从""改为null,匹配Autocomplete的未选中状态 - 给Autocomplete添加
value={data}属性,让组件状态与state保持同步 - 清空按钮点击时将
data设为null,触发Autocomplete清除选中状态 - 展示
data的标签用data || ""处理null值,避免页面显示"null"文本
内容的提问来源于stack exchange,提问作者Rio0o.dev
相关产品推荐
相关产品推荐

