Reactjs将props传递给2个组件

时间:2019-09-26 19:49:44

标签: javascript reactjs

在我的项目中,我有一个付款表格,该表格有条件地呈现2个Stripe元素(PaymentRequestForm.js和CheckoutForm.js),我已将Props从主要表格组件FullfillRequest.js传递到PaymentRequestForm.js,但是我努力将相同的道具传递给CheckoutForm.js。 道具的功能是使条纹付款完成后能够提交表格。

在当前设置下,错误是this.props.setComplete()在CheckoutForm.js中未定义。

FulfillRequest.js

  setComplete = val => {
    this.setState({
      complete: val
    });
  };

 render() {
return <PaymentRequestForm
setComplete={this.setComplete}
complete={this.state.complete}
requestId={this.props.requestId}
/>

  <Button disabled={loading || !this.state.complete} >
 Fulfill Request
</Button>
}

PaymentRequestForm.js

class PaymentRequestForm extends React.Component {
  constructor(props) {
    super(props);

   paymentRequest.on("token", async ev => {
      const response = await fetch();
      if (response.ok) {
            this.props.setComplete(true);
      } 
    });

    this.state = {
      canMakePayment: false,
      paymentRequest,
      complete: false
    };
  }

  render() {
    if (this.props.complete) return <h1>Purchase Complete</h1>;
     return this.state.canMakePayment ? (
      <PaymentRequestButtonElement />
    ) : (
      <CheckoutForm
        setComplete={this.setComplete}
        complete={this.state.complete}
        requestId={this.props.requestId}
      />
    );

CheckoutForm.js

class CheckoutForm extends Component {
  constructor(props) {
    super(props);
    this.state = { complete: false };
    this.submit = this.submit.bind(this);
  }
  async submit(ev) {
    let response = await fetch();
    if (response.ok) {
      this.props.setComplete(true);
       }
  }

  render() {
    if (this.props.complete) return <h1>Purchase Complete</h1>;
    return (
           <Button onClick={this.submit}>
            Send
          </Button>
       );
  }
}

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

内部PaymentRequstForm setComplete可以通过this.props.setComplete而不是this.setComplete访问(因为它来自FulfillRequest

  render() {
    if (this.props.complete) return <h1>Purchase Complete</h1>;
     return this.state.canMakePayment ? (
      <PaymentRequestButtonElement />
    ) : (
      <CheckoutForm
        setComplete={this.props.setComplete}
        complete={this.state.complete}
        requestId={this.props.requestId}
      />
    );