reactjs - 如果在 react-select 中选择了相同的选项,则不要触发 onChange
问题描述
当我在下拉列表中选择一个已选择的值时,会触发 react-select 下拉列表的onChange 。如果再次选择已选择的值,是否有办法将 react-select 配置为不触发onChange事件。
这是一个代码框链接。尝试选择紫色,您可以在控制台中看到日志。如果您想立即查看,下面是相同的代码。
import chroma from 'chroma-js';
import { colourOptions } from './docs/data';
import Select from 'react-select';
const dot = (color = '#ccc') => ({
alignItems: 'center',
display: 'flex',
':before': {
backgroundColor: color,
borderRadius: 10,
content: '" "',
display: 'block',
marginRight: 8,
height: 10,
width: 10,
},
});
const colourStyles = {
control: styles => ({ ...styles, backgroundColor: 'white' }),
option: (styles, { data, isDisabled, isFocused, isSelected }) => {
const color = chroma(data.color);
return {
...styles,
backgroundColor: isDisabled
? null
: isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null,
color: isDisabled
? '#ccc'
: isSelected
? chroma.contrast(color, 'white') > 2 ? 'white' : 'black'
: data.color,
cursor: isDisabled ? 'not-allowed' : 'default',
};
},
input: styles => ({ ...styles, ...dot() }),
placeholder: styles => ({ ...styles, ...dot() }),
singleValue: (styles, { data }) => ({ ...styles, ...dot(data.color) }),
};
const logConsole = (selectedVal) => {
console.log(selectedVal)
}
export default () => (
<Select
defaultValue={colourOptions[2]}
label="Single select"
options={colourOptions}
styles={colourStyles}
onChange={logConsole}
/>
);
解决方案
一种可能的解决方案是使用hideSelectedOptions
道具隐藏选定的值。
<Select
{ ... }
hideSelectedOptions
/>
另一种解决方案是将您的Select
组件更改为受控组件并检查onChange
处理程序,如果选定的值与当前选定的值匹配,则什么也不做。
class MySelect extends Component {
state = {
value: null
}
onChange = (selectedValue) => {
const { value } = this.state;
if (value && value.value === selectedValue.value) return;
// Do whatever you want here
this.setState({ value: selectedValue });
}
render = () => (
<Select
{ ... }
value={this.state.value}
onChange={this.onChange}
/>
);
}
推荐阅读
- java - 如何向洋葱服务器发送http请求?
- html - 布局菜单项,更改所选页面“项目”的样式
- prometheus-alertmanager - Alertmanager 中的指纹字段是否唯一?
- android - Ionic 4 与 Ionic 3 中的后台工作人员
- c# - BoundedChannel、BufferBlock 还是其他?
- react-native - reducer 返回状态,但未调用组件 getDerivedStateFromProps
- c# - 改源后UWP播放MediaElement
- sql - 在 SQL Server 2016 中使用 JSON 进行字符串聚合
- angular - 在 angular2 中使用 HttpParams 的 Http 获取返回 404 错误
- python - 我可以使用标记化的输入文件和高棉语的自定义词汇文件从头开始预训练 BERT 模型吗