I have created this React component called StateWithValidation.
import { useStateWithValidation } from "./useStateWithValidation"; export const StateWithValidation = () => { const [username, setUserName, isValid] = useStateWithValidation( (value: string) => value.length > 5, "" ); return ( <div> <div>Valid: {isValid.toString()}</div> <input type="text" value={username} onChange={(e) => setUserName(e.target.value)} /> </div> ); };
I have a custom hook which is generic, it validates and handles user input changes.
import { useCallback, useState } from "react"; type useStateValidationFn = <U>( validationFunc: (value: U) => boolean, initialState: U ) => [U, (nextState: U) => void, boolean]; export const useStateWithValidation: useStateValidationFn = ( validationFunc, initialValue ) => { const [state, setState] = useState(initialValue); const [isValid, setIsValid] = useState(() => validationFunc(state)); const onChange = useCallback( (nextState) => { setState(nextState); setIsValid(validationFunc(nextState)); }, [validationFunc] ); return [state, onChange, isValid]; };
Why is it when I type in the React component, the value of the generic type is "" instead of string.
Try changing as below
const [username, setUserName, isValid] = useStateWithValidation(
(value: string) => value.length > 5,
new String()
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.