我寻求帮助,了解如何传递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 回答
![?](http://img1.sycdn.imooc.com/5458655200013d9802200220-100-100.jpg)
噜噜哒
TA贡献1784条经验 获得超7个赞
您应该使用 GlobalConsumer 包装您的子组件,以便访问上下文值。像这样的东西:
<MyContext.Consumer>
{({toggleAuthError}) => /* render something based on the context value */}
</MyContext.Consumer>
然后您可以简单地将 传递toggleAuthError给 handleFormSubmit 函数。
添加回答
举报
0/150
提交
取消