当我尝试使用此页面上提供的示例在此处输入链接描述时,react 只是在第一行使用const color = chroma(data.color);
返回"未知格式"
import chroma from "chroma-js";
const runeColorStyles = {
control: styles => ({ ...styles, backgroundColor: 'white' }),
option: (styles, { data, isDisabled, isFocused, isSelected }) => {
const color = chroma(data.color); // First error is here
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',
':active': {
...styles[':active'],
backgroundColor: !isDisabled && (isSelected ? data.color : color.alpha(0.3).css()),
},
};
},
multiValue: (styles, { data }) => {
const color = chroma(data.color);
return {
...styles,
backgroundColor: color.alpha(0.1).css(),
};
},
multiValueLabel: (styles, { data }) => ({
...styles,
color: data.color,
}),
multiValueRemove: (styles, { data }) => ({
...styles,
color: data.color,
':hover': {
backgroundColor: data.color,
color: 'white',
},
}),
};
我不知道为什么这发生在我这边。这很奇怪,因为它在他们的示例页面中工作得很好。
我在使用 CreatableSelect 并尝试键入新选项时想到了这一点。我用const color = chroma(data.color ?? 'black');
来修复它。
const color = chroma(data.color);
第一步是将您的颜色转换为色度.js。这就是泛型构造函数 chroma(( 所做的。此函数尝试为您猜测输入颜色的格式。因此,data.color 需要有效的颜色。
colourStyles = {
control: styles => ({ ...styles, backgroundColor: 'white' }),
option: (styles, { data, isDisabled, isFocused, isSelected }) => {
const color = chroma(data.color);
return {
......
};
}
您传递给选项的 colorOption 对象将作为数据 -选项:(样式、{ 数据、isDisabled、isFocused、isSelected }(。如果颜色在 ColorOption 对象中不存在,它将通过错误"未知格式"。
<Select className="basic-single" classNamePrefix="select" defaultValue={colourOptions[0]}
isDisabled={isDisabled} isLoading={isLoading} isClearable={isClearable}
isRtl={isRtl} isSearchable={isSearchable} name="color"
options={colourOptions} <!-- colourOptions object -->
styles={colourStyles} />
颜色选项对象:
colourOptions:[
{ value: 'ocean', label: 'Ocean', color: '#00B8D9', isFixed: true },
{ value: 'blue', label: 'Blue', color: '#0052CC', isDisabled: true },
{ value: 'purple', label: 'Purple', color: '#5243AA' },
{ value: 'red', label: 'Red', color: '#FF5630', isFixed: true },
{ value: 'orange', label: 'Orange', color: '#FF8B00' },
{ value: 'yellow', label: 'Yellow', color: '#FFC400' },
{ value: 'green', label: 'Green', color: '#36B37E' },
{ value: 'forest', label: 'Forest', color: '#00875A' },
{ value: 'slate', label: 'Slate', color: '#253858' },
{ value: 'silver', label: 'Silver', color: '#666666' },
]
注意:确保颜色属性存在于颜色选项中。
工作演示:https://codesandbox.io/s/react-codesandboxer-example-zxqg0