我在尝试将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;