Skip to content

Commit

Permalink
feat(useControllableValue): 支持设置默认值
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 27, 2020
1 parent 96e942f commit e9fa831
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/react/useControllableValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@ import { useUpdateEffect } from 'react-use'
export type UseControllableValueResult<
TProps,
TValuePropName extends keyof TProps,
TCallbackPropName extends keyof TProps
> = [TProps[TValuePropName], Defined<TProps[TCallbackPropName]>]
TCallbackPropName extends keyof TProps,
TDefaultValue extends TProps[TValuePropName]
> = [
TDefaultValue extends undefined
? TProps[TValuePropName]
: Defined<TProps[TValuePropName]>,
Defined<TProps[TCallbackPropName]>,
]

/**
* 受控值。
Expand All @@ -20,20 +26,28 @@ export function useControllableValue<
TProps,
TDefaultValuePropName extends keyof TProps,
TValuePropName extends keyof TProps,
TCallbackPropName extends keyof TProps
TCallbackPropName extends keyof TProps,
TDefaultValue extends TProps[TValuePropName]
>(
props: TProps,
defaultValuePropName: TDefaultValuePropName,
valuePropName: TValuePropName,
callbackPropName: TCallbackPropName,
): UseControllableValueResult<TProps, TValuePropName, TCallbackPropName> {
defaultValue?: TDefaultValue,
): UseControllableValueResult<
TProps,
TValuePropName,
TCallbackPropName,
TDefaultValue
> {
const [value, setValue] = useState(() => {
if (valuePropName in props) {
return props[valuePropName]
}
if (defaultValuePropName in props) {
return props[defaultValuePropName]
}
return defaultValue
})

useUpdateEffect(() => {
Expand Down

0 comments on commit e9fa831

Please sign in to comment.