Skip to content

Instantly share code, notes, and snippets.

@Ray-56
Created December 1, 2021 10:21
Show Gist options
  • Save Ray-56/eec4d23e4ae458589ad29f4ca0eaa5d7 to your computer and use it in GitHub Desktop.
Save Ray-56/eec4d23e4ae458589ad29f4ca0eaa5d7 to your computer and use it in GitHub Desktop.
React Component 受空|非受控;value, defaultValue
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