美文网首页
React:自定义全局Loading

React:自定义全局Loading

作者: 精神病患者link常 | 来源:发表于2022-06-03 12:23 被阅读0次

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, "成功!")

相关文章

网友评论

      本文标题:React:自定义全局Loading

      本文链接:https://www.haomeiwen.com/subject/ppzcmrtx.html