从 selected 添加和删除项目时,如何在 react-select 中捕获添加和删除事件?
How to catch add and remove event in react-select when andding and removing item from selected?
handleChange(value) {
let difference = this.state.selected.filter(x => !value.includes(x));
console.log("Removed: ", difference);
this.setState({
selected: value
});
}
为了在 react-select 中获得有关 addition
值的通知,我使用了 onKeyDown
prop。当用户输入任何手动值并点击 enter
或 tab
以添加如下值时,将调用此方法 (handleKeyDown
):
<Select
inputValue={inputValue}
isClearable={false}
isMulti
onChange={this.handleChange}
onInputChange={this.handleInputChange}
onKeyDown={this.handleKeyDown}
placeholder="Type something and press enter..."
value={value}
/>
handleKeyDown = event => {
const { inputValue, value } = this.state;
if (!inputValue) return;
console.log("event.key:", event.key);
switch (event.key) {
case "Enter":
const newValues = inputValue.split(",").map(x => createOption(x));
this.setState({
inputValue: "",
value: [...value, ...newValues]
});
event.preventDefault();
break;
case "Tab":
this.setState({
inputValue: "",
value: [...value, createOption(inputValue)]
});
event.preventDefault();
break;
default:
console.log("Other events caught");
}
};
您可以使用 onChange
道具捕获 remove
事件。下面的代码显示:
handleChange = (value, actionMeta) => {
console.group("Inside handleChange");
console.log(value);
console.log(`action: ${actionMeta.action}`); // will capture remove event
this.setState({ value });
};
您可以在下面的沙箱中进行试验。上述示例存在于沙箱中:https://codesandbox.io/s/react-codesandboxer-example-7r2y6
handleChange(value) {
let difference = this.state.selected.filter(x => !value.includes(x));
console.log("Removed: ", difference);
this.setState({
selected: value
});
}
为了在 react-select 中获得有关 addition
值的通知,我使用了 onKeyDown
prop。当用户输入任何手动值并点击 enter
或 tab
以添加如下值时,将调用此方法 (handleKeyDown
):
<Select
inputValue={inputValue}
isClearable={false}
isMulti
onChange={this.handleChange}
onInputChange={this.handleInputChange}
onKeyDown={this.handleKeyDown}
placeholder="Type something and press enter..."
value={value}
/>
handleKeyDown = event => {
const { inputValue, value } = this.state;
if (!inputValue) return;
console.log("event.key:", event.key);
switch (event.key) {
case "Enter":
const newValues = inputValue.split(",").map(x => createOption(x));
this.setState({
inputValue: "",
value: [...value, ...newValues]
});
event.preventDefault();
break;
case "Tab":
this.setState({
inputValue: "",
value: [...value, createOption(inputValue)]
});
event.preventDefault();
break;
default:
console.log("Other events caught");
}
};
您可以使用 onChange
道具捕获 remove
事件。下面的代码显示:
handleChange = (value, actionMeta) => {
console.group("Inside handleChange");
console.log(value);
console.log(`action: ${actionMeta.action}`); // will capture remove event
this.setState({ value });
};
您可以在下面的沙箱中进行试验。上述示例存在于沙箱中:https://codesandbox.io/s/react-codesandboxer-example-7r2y6