fix: color input infinite loop

pull/5899/head
Peng Xiao 2022-06-30 10:54:43 +08:00
parent 42f33d56f9
commit 1a5c60f85f
1 changed files with 11 additions and 4 deletions

View File

@ -7,15 +7,22 @@ interface ColorInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
export function ColorInput({ label, value, onChange, ...rest }: ColorInputProps) {
const ref = React.useRef<HTMLDivElement>(null)
const [computedValue, setComputedValue] = React.useState(value)
let varName: string | undefined
// TODO: listen to theme change?
if (value?.toString().startsWith('var') && ref.current) {
const varName = /var\((.*)\)/.exec(value.toString())?.[1]
varName = /var\((.*)\)/.exec(value.toString())?.[1]
if (varName) {
setComputedValue(getComputedStyle(ref.current).getPropertyValue(varName).trim())
const newValue = getComputedStyle(ref.current).getPropertyValue(varName).trim();
if (newValue !== computedValue) {
setComputedValue(newValue)
}
}
}
if (varName) {
return null
}
return (
<div className="input" ref={ref}>
<label htmlFor={`color-${label}`}>{label}</label>
@ -25,7 +32,7 @@ export function ColorInput({ label, value, onChange, ...rest }: ColorInputProps)
name={`color-${label}`}
type="color"
value={computedValue}
onChange={(e) => {
onChange={e => {
setComputedValue(e.target.value)
onChange?.(e)
}}