generated from arvinxx/npm-template
-
Notifications
You must be signed in to change notification settings - Fork 29
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
♻️ refactor: 移除 use-merge-value 依赖,避免依赖安装报 peer 错误
close #27
- Loading branch information
Showing
3 changed files
with
43 additions
and
5 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import React from 'react'; | ||
|
||
export const useMergeValue = <T, R = T>( | ||
defaultStateValue: T | (() => T), | ||
option?: { | ||
defaultValue?: T | (() => T); | ||
value?: T; | ||
onChange?: (value: T, prevValue: T) => void; | ||
postState?: (value: T) => T; | ||
}, | ||
): [R, (value: T) => void] => { | ||
const { defaultValue, value, onChange, postState } = option || {}; | ||
const [innerValue, setInnerValue] = React.useState<T>(() => { | ||
if (value !== undefined) { | ||
return value; | ||
} | ||
if (defaultValue !== undefined) { | ||
return typeof defaultValue === 'function' ? (defaultValue as any)() : defaultValue; | ||
} | ||
return typeof defaultStateValue === 'function' | ||
? (defaultStateValue as any)() | ||
: defaultStateValue; | ||
}); | ||
|
||
let mergedValue = value !== undefined ? value : innerValue; | ||
if (postState) { | ||
mergedValue = postState(mergedValue); | ||
} | ||
|
||
function triggerChange(newValue: T) { | ||
setInnerValue(newValue); | ||
if (mergedValue !== newValue && onChange) { | ||
onChange(newValue, mergedValue); | ||
} | ||
} | ||
|
||
return [mergedValue as unknown as R, triggerChange]; | ||
}; |