我寻求帮助,了解如何传递props到上下文提供从内部的function一个的child组成部分。
我有一个全局提供程序,我想data从表单中保存它,更具体地说error是onSubmit失败时的数据。
使用createContext我有一个全球供应商
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?
噜噜哒
相关分类