React.js使用Stripe更改状态:根据组件更改数量状态

时间:2018-10-02 22:00:49

标签: javascript reactjs stripe-payments react-state-management

我正在使用Reactjs上的Stripe开发支付系统。 CheckoutForm有两个父组件:每个组件都应包含用于其他订阅/定价计划的表单。因此,我想更改 amount 对象(在CheckoutForm中创建)的状态,具体取决于它是哪个父组件->,然后将其发送到服务器(付款在哪里)完成。 例如:Parent1:金额:2000;父母2:5000。

换句话说,我想将它从子级传递给父级,因此父级需要向子级提供设置父级状态的函数/方法。然后,我需要在子组件中调用该函数(我认为呢?)。

任何帮助将不胜感激!让我知道是否需要更多代码段。

class CheckoutForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      complete: false,
      referrer: '',
      email: '',
      amount: '',
    };
    this.submit = this.submit.bind(this);
  }

  componentDidMount() {
    console.log(this.props);
    let referrer = this.props.match.params.referrer; // url - added route to index.js
    if (referrer) {
      console.log(referrer);
      this.setState({ referrer, });
    }
  }

  // user clicked submit
  submit(ev) {
    ev.preventDefault(); // prevent default submission and refreshing the page
    this.props.stripe.createToken() // which elements to tokenize
      .then(response => {
        console.log('Received Stripe token:', response.token);
        axios.post('http://10.250.57.37:8000/subscriptions/codes/pay/',
          {
            token: response.token,
            amount: this.state.amount,
            email: this.state.email,
            referrer: this.state.referrer,
          },
          {
            'Content-Type': 'application/json', // header
          }
        )
        .then(response => {
          console.log(response);
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    if (this.state.complete) return <p>Purchase Complete!</p>;

    return (
      <div className="checkout-form">
        <PrimeHeading
          heading={this.props.heading}
          subheading={this.props.subheading}
        />
        <p>Would you like to complete the purchase?</p>
        <form onSubmit={this.submit} style={{ minHeight: 300, }}>
          <label>
            Email
            <input
              id="email"
              name="email"
              type="email"
              placeholder="Enter your email"
              required
              onChange={this._handleEmailChange.bind(this)}
              value={this.state.email}
            />
          </label>
          {/* <label>
            Referral
            <input
              id="referrer"
              name="referrer"
              type="text"
              placeholder="Enter your friends' usernames"
              required
            />
          </label> */}
          <CheckoutCardSection />
          <Button
            // label="Pay" {this.state.amount} "DKK"
            onClick={this.submit}
            type="button"
            size="medium"
            backgroundColor="#43ddb1"
            color="white"
            noShadow
          />
        </form>
        {this.state.code && <div>Your activation code is: {this.state.code} and it is valid for {this.state.subscription_days} days.</div>}
      </div>
    );
  }

  _handleEmailChange(event) {
    let email = event.target.value;
    this.setState({ email, });
  }
  

1 个答案:

答案 0 :(得分:0)

如果我不理解您的意思,您想重用CheckoutForm组件。如您所想,您可以将处理函数传递给CheckoutForm来更新父组件。一个非常基本的例子:

class CheckoutForm extends React.Component {
  state = {
    amount: "",
  };

  handleChange = e => this.setState( { amount: e.target.value } );
  handleSubmit = ( e ) => {
    e.preventDefault();
    this.props.handleAmount( this.state.amount );
  };

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.handleChange} />
          <button>Send</button>
        </form>
      </div>
    );
  }
}

class Parent1 extends React.Component {
  state = {
    amount: "",
  };

  handleAmount = amount => this.setState( { amount } );

  render() {
    return (
      <div>
        <CheckoutForm handleAmount={this.handleAmount} />
        <p>This is Parent1 component</p>
        My amount is: {this.state.amount}
      </div>
    );
  }
}

class Parent2 extends React.Component {
  state = {
    amount: "",
  };

  handleAmount = amount => this.setState( { amount } );

  render() {
    return (
      <div>
        <CheckoutForm handleAmount={this.handleAmount} />
        <p>This is Parent2 component</p>
        My amount is: {this.state.amount}
      </div>
    );
  }
}

class App extends React.Component {
  state = {
    amount: "",
  };

  render() {
    return (
      <div>
        <Parent1 />
        <hr />
        <Parent2 />
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>