javascript - 从javascript / typescript中的另一个函数访问函数的参数
问题描述
如何从另一个函数访问 lambda 函数的参数?
我正在尝试从函数访问formikBag
, created inside的值。render={...}
handleClick
我首先尝试使用useState
钩子设置状态,然后访问它,但我得到了undefined
.
export const Form: React.FC<FormProps> = (props) => {
const MyFormikForm = () => {
return (
<Formik
initialValues={...}
onSubmit={...)
validationSchema={.}
render={(formikBag: FormikProps<FormValues>) => <form>My Form</form>}
/>
)
}
const handleClick = () => {
showModal(({ show }) => {
// How could I get access the formikBag variable here?
// do stuff
return (
<ModalAntd>
<MyFormikForm />
</ModalAntd>
)
})
}
return <ButtonComponent onClick={handleClick} />
}
解决方案
您需要重新排列组件层次结构才能正确执行此操作。通过将您的模态包装在Formik
组件中(而不是相反),您可以访问 Formik 包或您需要的任何其他东西。
我不完全确定我完全理解你在做什么,但我认为这很接近:
/**
* Form that can appear in a modal or directly.
*/
function ExampleForm({
isSubmitting,
showButton
}: {
isSubmitting: boolean;
showButton: boolean;
}) {
return (
<Form>
<label htmlFor="field">Some Field</label>
<Field name="field" type="text" />
{showButton && (
<Button loading={isSubmitting} htmlType="submit">
Submit
</Button>
)}
</Form>
);
}
/**
* Show a form in a modal or directly.
*/
class ExampleFormWrapper extends React.PureComponent<
{ showModal: boolean },
{ isOpen: boolean }
> {
state = { isOpen: false };
/**
* Close the modal form.
*/
hideForm = () => this.setState({ isOpen: false });
/**
* Open the form in a modal.
*/
openForm = () => this.setState({ isOpen: true });
/**
* Submit the form with fake wait to simulate a real submission.
*/
onSubmit = (
values: FormValues,
{ setSubmitting }: FormikActions<FormValues>
) => {
console.log(values);
window.setTimeout(() => {
if (this.props.showModal) {
this.hideForm();
} else {
setSubmitting(false);
}
}, 2000);
};
/**
* Render either a form or a button that will show the form in a modal.
*/
render() {
return (
<React.Fragment>
{this.props.showModal && <Button onClick={this.openForm}>Open</Button>}
<Formik initialValues={{ field: "" }} onSubmit={this.onSubmit}>
{({ handleSubmit, isSubmitting }) =>
this.props.showModal ? (
<Modal
onCancel={this.hideForm}
onOk={handleSubmit}
okButtonProps={{ loading: isSubmitting }}
okText="Submit"
title="Form"
visible={this.state.isOpen}
>
<ExampleForm isSubmitting={isSubmitting} showButton={false} />
</Modal>
) : (
<ExampleForm isSubmitting={isSubmitting} showButton={true} />
)
}
</Formik>
</React.Fragment>
);
}
}
我以前从未使用过 Ant,但是它们的模态组件的设计使这变得更加困难。
推荐阅读
- laravel - 如何在 vuejs + laravel 中检索复选框值
- apache-kafka - Kafka:使用普通消费者组访问多个主题
- git - 如何将 GitLab 的 CI 子模块设置指定为仅在主分支上使用提交?
- angular - 无法从 ngOnInit() 访问类变量
- csv - 如何在 pyspark 中附加 2 个数据帧并将两个标题都保留在第一行和第二行?或者将第二个标头添加到已经有 1 个标头的数据帧中?
- javascript - CSV 格式的 Angular 数据中的逗号相关问题
- python - WebElement 和 __getitem__ 有什么问题
- node.js - ts-node-dev 脚本没有错误,但 SERVERLESS 离线(和部署)脚本发生错误
- r - 在 R 中使用 httr 的 HTTP POST
- azure - 尝试将 BACPAC 从 blob 存储导入到 ssms 时收到 CREATE USER 错误