Passing props to Higher-Order Component

微笑、不失礼 提交于 2019-12-30 07:10:28

问题


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?


回答1:


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




回答2:


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:


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.



来源:https://stackoverflow.com/questions/53818564/passing-props-to-higher-order-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!