簡體   English   中英

將道具傳遞給高階組件

[英]Passing props to Higher-Order Component

我有一個高階組件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函數作為WrappedComponent的prop WrappedComponentFormBuilder以便在提交表單時可以調用它。 我決定在WrappedComponent定義onSubmit函數的WrappedComponent是因為我有另一個具有onSubmit函數的WrappedComponent (使用FormBuilder )但是它發送了一個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“submit”以傳遞方法。

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

我想我們可能需要更多關於項目結構的信息,但是你可以在FormBuilder( funcA )中創建一個函數,傳遞給WrappedComponent,它將函數作為參數。 然后當你單擊WrappedComponent中的按鈕時,它會將自己的onSubmit函數發送回funcA ,它可以在FormBuilder中使用。

然后可以在您的其他WrappedComponent(使用POST請求)上使用它,因為您將從兩者中發送onSubmit函數以在FormBuilder中調用。

希望這可以幫助。

我不確定這是否可行,但也許你可以將表單提交的結果保存到HOC的狀態,然后通過props將這些信息傳遞給WrappedComponent 然后在WrappedComponent使用getDerivedStateFromProps ,您可以將提交的表單信息傳遞給組件的提交函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM