React:自定义全局Loading

2022-06-03  本文已影响0人  精神病患者link常

1.通过使用createContext创建LoadingProvider包裹App,添加LoadingComponent,和App同级显示。定义showhide方法。
2.子组件通过useContext获取对象,调用showhide进行显示和隐藏

1. 创建LoadingProvider

export const LoadingContext = createContext({
    show: (type:LoadingType,message:string) => {
    },
    hide:()=>{}
})

export default function LoadingProvider({children}:any) {
    const [visible,setVisible] = useState(false)
    const typeRef = useRef()
    const messageRef = useRef()
    return(
        <LoadingContext.Provider
            value={{
                show:(type, message) => {
                   typeRef.current = type
                    messageRef = type
                    setVisible(true)
                },
                hide:()=>{
                    setVisible(false)
                }
            }} >
          {children}
          <LoadingModal
            visible={visible}
            type={type}
            message={message}
            onClose={()=>setVisible(false)}/>
        </LoadingContext.Provider>
    )
}

2.包裹整个App

<LoadingProvider>
  <App/>
</LoadingProvider>

3.页面中使用

导入 LoadingContext
const loading = useContext(LoadingContext)
loading.show(LoadingType.success, "成功!")
上一篇 下一篇

猜你喜欢

热点阅读