Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

javascript - Making hex 3-digit converts it to 6-digits while using `rgb-hex` library as an input in React JS?

I am using react-colorful & using it's <HexColorInput /> component as:

<HexColorInput
    className="w-12 text-blue-gray-500"
    color={rgb2hex(selectedColor.rgba)}
    onChange={(hex: string) => {
        updateBackground({
            selectedColor: {
                ...selectedColor,
                rgba: hex2rgb(hex),
            },
        })
    }}
/>

The color prop acts similar to value prop on input. And onChange handler changes as you type in an input.

The problem right now is when I make the hex input to be 3-digits, it automatically converts it to 6-digits as I'm directly using rgb2hex function on the input.

How do I fix this?

Codesandbox → https://codesandbox.io/s/react-colorful-sketch-picker-ouz5t

question from:https://stackoverflow.com/questions/65933032/making-hex-3-digit-converts-it-to-6-digits-while-using-rgb-hex-library-as-an-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The common way to declare a hex color is using 6 digits. When using the 3 digits format, you are shortening the 6 digits format. This only works if the digits in the positions R (so 1,2), G (3,4) and B(5,6) are equals.

Eg: You can write #00CCFF in 3 digits format as #0CF, but you cannot do the same on #425416

Maybe this thread can make my point more clear.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...