我有一个像这样的高阶组件FormBuilder
:
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
: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
函数作为 Prop 从WrappedComponent
发送到FormBuilder
,以便在提交表单时可以调用它。我决定在onSubmit
中定义WrappedComponent
函数的原因是因为我还有另一个具有WrappedComponent
函数的FormBuilder
(使用onSubmit
),但它发送的是PATCH请求而不是POST请求。我该如何实现? 最佳答案
您可以执行以下操作:
function logProps(InputComponent) {
InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
};
// The fact that we're returning the original input is a hint that it has
// been mutated.
return InputComponent;
}
// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);
作为参数,您可以添加 Prop “提交”以传递方法。
引用:https://reactjs.org/docs/higher-order-components.html#dont-mutate-the-original-component-use-composition