我用的是react-colorful &使用它的<HexColorInput />
组件作为:
<HexColorInput
className="w-12 text-blue-gray-500"
color={rgb2hex(selectedColor.rgba)}
onChange={(hex: string) => {
updateBackground({
selectedColor: {
...selectedColor,
rgba: hex2rgb(hex),
},
})
}}
/>
color
prop对input
的作用与value
prop相似。onChange
处理程序在您输入输入时发生变化。
现在的问题是,当我使十六进制输入是3位数字,它会自动转换为6位数字,因为我直接使用rgb2hex
函数的输入。
如何解决这个问题?
Codesandbox→https://codesandbox.io/s/react-colorful-sketch-picker-ouz5t
声明十六进制颜色的常用方法是使用6位数字。使用3位数格式时,缩短了6位数格式。只有当位置R (1,2), G(3,4)和B(5,6)上的数字相等时才有效。
例如:您可以将#00CCFF
写成3位数格式的#0CF
,但您不能在#425416
上这样做
也许这个帖子可以让我的观点更清楚。
我只需要检查hex.length
是否等于4
&如果是,则Ireturn
:
<HexColorInput
className="w-12 text-blue-gray-500"
color={rgb2hex(selectedColor.rgba)}
onChange={(hex: string) => {
if (hex.length === 4) return
updateBackground({
selectedColor: {
...selectedColor,
rgba: hex2rgb(hex),
},
})
}}
/>
HexColorInput
的源代码特别将#
添加到它中,因此对于任何3位十六进制,它使其成为4位。
编辑:
如果我在HexColorInput
包含像#21b
这样的3位数值时模糊,则上述答案不会返回到以前的值,因此我克隆了HexColorInput
&删除了支持3位十六进制的验证。
我的新HexInput.tsx
看起来像:
import React from 'react'
import { useEventCallback } from '../hooks'
const hex6 = /^#?[0-9A-F]{6}$/i
const validHex = (color: string): boolean => hex6.test(color)
// Escapes all non-hexadecimal characters including "#"
const escapeNonHex = (hex: string) => hex.replace(/([^0-9A-F]+)/gi, '').substr(0, 6)
type ComponentProps = {
hex: string
onChange: (newColor: string) => void
}
type InputProps = Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'>
export const HexInput = ({
hex = '',
onChange,
onBlur,
...rest
}: Partial<InputProps & ComponentProps>) => {
const [value, setValue] = React.useState(() => escapeNonHex(hex))
const onChangeCallback = useEventCallback<string>(onChange)
const onBlurCallback = useEventCallback<React.FocusEvent<HTMLInputElement>>(onBlur)
// Trigger `onChange` handler only if the input value is a valid HEX-color
const handleChange = React.useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const inputValue = escapeNonHex(e.target.value)
setValue(inputValue)
if (validHex(inputValue)) onChangeCallback('#' + inputValue)
},
[onChangeCallback]
)
// Take the color from props if the last typed color (in local state) is not valid
const handleBlur = React.useCallback(
(e: React.FocusEvent<HTMLInputElement>) => {
if (!validHex(e.target.value)) setValue(escapeNonHex(hex))
onBlurCallback(e)
},
[hex, onBlurCallback]
)
// Update the local state when `color` property value is changed
React.useEffect(() => {
setValue(escapeNonHex(hex))
}, [hex])
return (
<input
{...rest}
value={value}
spellCheck="false" // the element should not be checked for spelling errors
onChange={handleChange}
onBlur={handleBlur}
/>
)
}
下面是完整的示例和演示→https://codesandbox.io/s/react-colorful-sketch-picker-ouz5t?file=/src/HexRgbaBox/HexInput.tsx