将道具传递给高阶组件 [英] Passing props to Higher-Order Component
问题描述
我有一个更高阶的组件 FormBuilder
,如下所示:
I have a higher-order component FormBuilder
like this:
const FormBuilder = (WrappedComponent) => {
return class HOC extends React.Component {
clearForm() { // ... }
render() {
return (
<Form onSubmit={//what do I say here?!}>
<Form.Input placeholder='Name' name='name' />
<WrappedComponent clearForm={this.clearForm} />
<Form>
);
}
}
}
这里是WrappedComponent NewPizzaForm
:
And here is the WrappedComponent NewPizzaForm
:
class WrappedComponent extends React.Component {
onSubmit() { // sends a POST request to the backend, then this.props.clearForm() }
render() {
return (
<Form.Button>Add Pizza</Form.Button>
);
}
}
const NewPizzaForm = FormBuilder(WrappedComponent);
export default NewPizzaForm;
所以我想发送 onSubmit
函数作为 WrappedComponent
中的支柱到 FormBuilder
,以便在提交表单时可以进行调用。我决定在 WrappedComponent
中定义 onSubmit
函数的原因是因为我有另一个 WrappedComponent
(使用 FormBuilder
)具有 onSubmit
函数,但它发送PATCH请求而不是POST请求。我如何实现这一目标?
So I want to send the onSubmit
function as a prop from the WrappedComponent
to the FormBuilder
so that it is available for call when the form is submitted. And the reason I decided to define the onSubmit
function inside WrappedComponent
is because I have another WrappedComponent
(uses FormBuilder
) that has the onSubmit
function but it sends a PATCH request rather than POST request. How do I achieve this?
推荐答案
我不确定这是否有用,但也许你可以保存结果提交到HOC状态的表单,然后通过props将该信息传递给 WrappedComponent
。然后在 WrappedComponent
中使用 getDerivedStateFromProps
,您可以将提交的表单信息传递给组件的提交函数。
I'm not at all sure if this would work, but maybe you could save the result of the form submission into the HOC's state, and then pass that information down to WrappedComponent
via props. Then using getDerivedStateFromProps
inside of WrappedComponent
, you can pass the submitted form information into the component's submit function.
这篇关于将道具传递给高阶组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!