Passing props to Higher-Order Component

2019-02-15 14:31发布

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>
      );
    }
  }
}

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;

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?

3条回答
We Are One
2楼-- · 2019-02-15 15:11

I think we might need a little more information about the structure of your project, but you could create a function within FormBuilder (funcA) that you pass down to the WrappedComponent that takes a function as an argument. Then when you click the button within WrappedComponent, it would send its own onSubmit function back up to funcA where it can be used within FormBuilder.

This can then be used on your other WrappedComponent (with the POST request) as you would just be sending the onSubmit function from both to be called within FormBuilder.

Hope this helps.

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-15 15:12

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.

查看更多
Anthone
4楼-- · 2019-02-15 15:29

You can act as following:

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);

As parameter you can add the prop "submit" to pass in the method.

Ref: https://reactjs.org/docs/higher-order-components.html#dont-mutate-the-original-component-use-composition

查看更多
登录 后发表回答