Created
December 1, 2021 10:21
-
-
Save Ray-56/eec4d23e4ae458589ad29f4ca0eaa5d7 to your computer and use it in GitHub Desktop.
React Component 受空|非受控;value, defaultValue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef, useState } from 'react'; | |
// 解决“受控组件*******”报错 | |
function fixControlledValue(value: string) { | |
if (typeof value === 'undefined' || value === null) return ''; | |
return value; | |
} | |
interface InputProps { | |
/** 不受控 */ | |
defaultValue?: string; | |
/** 受控 */ | |
value?: string; | |
onChange?: (value: string) => void; | |
} | |
const Input: React.FC<InputProps> = (props) => { | |
const { defaultValue, value, onChange } = props; | |
const cacheState = useRef<string>(value); | |
const [currentValue, setCurrentValue] = useState( | |
typeof value === 'undefined' ? defaultValue : value | |
); | |
useEffect(() => { | |
if (cacheState.current !== value) { | |
setCurrentValue(value); | |
cacheState.current = value; | |
} | |
}, [value]); | |
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { | |
const val = e.target.value; | |
if (value === undefined) { | |
setCurrentValue(val); | |
} | |
onChange?.(val); | |
}; | |
return ( | |
<input placeholder="我是占位符" value={fixControlledValue(currentValue)} onChange={handleChange} /> | |
); | |
}; | |
export default Input; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment