我尋求幫助,了解如何傳遞props到上下文提供從內(nèi)部的function一個的child組成部分。我有一個全局提供程序,我想data從表單中保存它,更具體地說error是onSubmit失敗時的數(shù)據(jù)。使用createContext我有一個全球供應(yīng)商import React, { createContext } from 'react';interface InterfaceProps { children?: any;}interface InterfaceState { error: any; toggleAuthError: any;}const GlobalContext = createContext({ error: null, toggleAuthError: () => {}});export class GlobalProvider extends React.Component<InterfaceProps, InterfaceState> { public toggleAuthError = ({ authError }: any) => { this.setState({ error: authError }); }; public state = { error: null, toggleAuthError: this.toggleAuthError }; public render() { const { children } = this.props; return <GlobalContext.Provider value={this.state as any}>{children}</GlobalContext.Provider>; }}export const GlobalConsumer = GlobalContext.Consumer;然后在我的表單child組件中,我有一個名為onSubmit.public handleFormSubmit = async (data: { email: string; password: string }) => { const { form } = this.props; const { email, password } = data; await form ... .catch((error: any) => { toggleAuthError(error); // Want this to trigger the function and pass error to the context provider this.setState({ loading: false }); }); };如何在上下文提供程序中傳遞error給this.toggleAuthError?
將 props 從函數(shù)傳遞給全局上下文提供者
元芳怎么了
2021-08-26 17:11:52