为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

元芳怎么了 2021-08-26 17:11:52
我寻求帮助,了解如何传递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?
查看完整描述

2 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

您应该使用 GlobalConsumer 包装您的子组件,以便访问上下文值。像这样的东西:


<MyContext.Consumer>

  {({toggleAuthError}) => /* render something based on the context value */}

</MyContext.Consumer>

然后您可以简单地将 传递toggleAuthError给 handleFormSubmit 函数。


查看完整回答
反对 回复 2021-08-26
  • 2 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信