我正在尝试向我的反应选择组件添加一个编辑按钮(当前触发警报)。然而,这使得新添加的按钮无法点击;相反,它会打开反应选择菜单。停止传播并不能解决问题。
const CustomOption = (props) => {
const handleEdit = (e) => {
e.stopPropagation();
alert("This is working like I want");
};
return (
<components.Option {...props}>
<div className="test">
<span>{props.children}</span>
<button onClick={handleEdit}>Edit</button>
</div>
</components.Option>
);
};
export default function App() {
const option = [
{ value: "Spring", label: "Spring" },
{ value: "Summer", label: "Summer" },
{ value: "Autumn", label: "Autumn" },
{ value: "Winter", label: "Winter" },
];
return (
<div className="App">
<Select
className="dropdown"
options={option}
components={{ SingleValue: CustomSingleValue }}
/>
</div>
);
}
问题: 为什么 CustomSingleValue 中的按钮不起作用(而 CustomOption 中的按钮可以),我该如何修复它?
这尤其令人沮丧,因为使用完全相同的代码的 CustomOption 工作得很好。
完整代码,包括工作自定义选项:
// This isn't working like I want
const CustomSingleValue = (props) => {
const handleEdit = (e) => {
e.stopPropagation();
alert("This I can't click");
};
return (
<components.SingleValue {...props}>
<div className="test">
<span>{props.children}</span>
<div>
<button onClick={handleEdit}>Edit</button>
</div>
</div>
</components.SingleValue>
);
};
// This is working how I want
const CustomOption = (props) => {
const handleEdit = (e) => {
e.stopPropagation();
alert("This is working like I want");
};
return (
<components.Option {...props}>
<div className="test">
<span>{props.children}</span>
<button onClick={handleEdit}>Edit</button>
</div>
</components.Option>
);
};
export default function App() {
const option = [
{ value: "Spring", label: "Spring" },
{ value: "Summer", label: "Summer" },
{ value: "Autumn", label: "Autumn" },
{ value: "Winter", label: "Winter" },
];
return (
<div className="App">
<Select
className="dropdown"
options={option}
placeholder="Click on a option and then try to click the edit button"
components={{ SingleValue: CustomSingleValue, Option: CustomOption }}
/>
</div>
);
}
这很可能是因为 Select 组件阻止了单击事件在当前选定的选项内传播。