gpt4 book ai didi

javascript - 使用 Material UI 访问 renderValue 组件上的 react 事件处理程序时出现问题

转载 作者:行者123 更新时间:2023-12-02 22:12:38 30 4
gpt4 key购买 nike

我正在尝试使用以下代码片段中的 Material UI 访问 chip 组件中的 onDelete 事件处理程序。

当我点击chip时,会发生Select行为(打开下拉菜单)。

有什么方法可以覆盖此行为,以便我也可以删除芯片吗?

代码沙箱演示:https://codesandbox.io/s/purple-thunder-s0isr

<Select
labelId="demo-mutiple-chip-label"
id="demo-mutiple-chip"
key=""
multiple
value={["Fred", "Tom"]}]
input={<Input id="select-multiple-chips" />}
renderValue={() =>
["Fred", "Tom"].map((name) => (
<Chip
label={name}
key={name}
onDelete={() => {
console.log("Delete clicked")
}}
/>
))
}
></Select>

最佳答案

查看示例:

import React, {useState} from "react";
import ReactDOM from "react-dom";
import { Select, Chip, Input, MenuItem } from "@material-ui/core";

import "./styles.css";

function App() {

const [chipData, setChipData] = React.useState([
{ key: 0, label: 'A' },
{ key: 1, label: 'B' },
{ key: 2, label: 'C' },
{ key: 3, label: 'D' },
{ key: 4, label: 'E' }
]);

const [selectedChips, setSelectedChips] = React.useState([]);
const [chipName, setChipName] = React.useState([]);
const [canOpen, setCanOpen] = React.useState(false);

const handleDelete = chipToDelete => () => {
let s = selectedChips.filter(chip => chip.key !== chipToDelete.key);
setSelectedChips(s);
setChipName(s);
};

const selectHandleOnOpen = event =>{
setCanOpen(!canOpen);
}

const handleChange = event => {
setChipName(event.target.value);
setSelectedChips(event.target.value);
};


return (

<Select
style={{width: "300px"}}
labelId="demo-mutiple-chip-label"
id="demo-mutiple-chip"
multiple
onChange={handleChange}
value={chipName}
onClick={selectHandleOnOpen}
open={canOpen}
renderValue={selected =>
selectedChips.map(item => (
<Chip
clickable={true}
label={item.label}
key={item.key}
onDelete={handleDelete(item)}
style={{margin: "5px"}}
/>

))
}

>
{chipData.map(item => (
<MenuItem key={'MenuItem-'+item.key} value={item} >
{item.label}
</MenuItem>
))}
</Select>

);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

请参阅此处的示例输出:https://codesandbox.io/s/flamboyant-saha-felni

关于javascript - 使用 Material UI 访问 renderValue 组件上的 react 事件处理程序时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59512931/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com