context 基础框架
ValidatorProvider 以校验器为例
import React, { useContext, useReducer } from 'react'
interface ReducerType {
isValidate?: boolean
}
interface InitData {
state: ReducerType
actions: {
validator: (callback?: () => void) => void
}
}
interface PropsType {
children?: any
[key: string]: any
}
const ValidatorContext = React.createContext<InitData | null>(null)
const reducerData: ReducerType = {
isValidate: false
}
const reducer = (
state: ReducerType,
action: { type: string; payload: ReducerType }
) => {
switch (action.type) {
case 'info':
return Object.assign({}, state, action.payload)
default:
return state
}
}
const ValidatorProvider = (props: PropsType) => {
const [state, dispatch] = useReducer(reducer, reducerData)
const dispatchFun = (payload: ReducerType) =>
dispatch({ type: 'info', payload })
const validator = (callback?: () => void) => {
dispatchFun({ isValidate: true })
setTimeout(() => dispatchFun({ isValidate: false }))
}
const ValidatorContextValue = {
state,
actions: {
validator
}
}
return (
<ValidatorContext.Provider value={ValidatorContextValue}>
{props.children}
</ValidatorContext.Provider>
)
}
const withProvider = (Comp: any, options?: PropsType) => {
return React.forwardRef((props, ref: any) => {
return (
<ValidatorProvider {...(options || {})}>
<Comp {...props} ref={ref} />
</ValidatorProvider>
)
})
}
const useValidatorContext = () => {
const context = useContext(ValidatorContext)
if (!context) {
throw new Error('useValidator must use in ValidatorContext')
}
return context
}
export { useValidatorContext, ValidatorProvider, withProvider }