如何向展示者展示FunctionComponent的功能?

时间:2019-06-02 06:01:35

标签: reactjs typescript react-hooks

我在尝试将FunctionComponent的嵌套函数公开给演示者时遇到麻烦。但是,这对于ClassComponent来说很好用。如果我想使用markFormAsDirty来使用钩子,还应该如何评估Presenter中的FunctionComponent嵌套函数?花了很多时间试图解决这个问题。我的最终目标是使用FunctionComponent而不是ClassComponent,这样我就可以在整个项目中开始使用钩子。

SignInComponent

const SignIn: React.FC<Props> = (props: Props) => {
    const [state, setState] = React.useState<SignInState>({
        pristine: true,
        username: "",
        password: ""
    });

    // --- I want presenter to be able to invoke this
    const markFormAsDirty = () => {
        setState({ ...state, pristine: false });
    };

    return (
        <div className="sign-in-container">
            // markup stuffs
        </div>
    );
};

export default WithPresenter(SignIn, SignInPresenter);

SignInPresenter

class SignInPresenter implements Presenter {
    view: any; // typed it to any just temporarily

    constructor(view: any) {
        this.view = view;
    }

    public validateFields = (username: string, password: string) => {
        if (this._isValidUsername(username) && password) {
            this.view.markFormAsDirty(); <-- this is undefined if I use FunctionComponent
        } else {
            alert("invalid");
        }
    };
}

export default SignInPresenter;

0 个答案:

没有答案