将 props 从函数传递给全局上下文提供者

我寻求帮助,了解如何传递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?


元芳怎么了
浏览 156回答 2
2回答

噜噜哒

您应该使用 GlobalConsumer 包装您的子组件,以便访问上下文值。像这样的东西:<MyContext.Consumer>&nbsp; {({toggleAuthError}) => /* render something based on the context value */}</MyContext.Consumer>然后您可以简单地将 传递toggleAuthError给 handleFormSubmit 函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript