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 })

  // 触发组件内部校验函数,触发之后将 isValidate 置为 false
  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 }
powered by Gitbook该文件修订时间: 2023-08-25 18:11:27

results matching ""

    No results matching ""