Reactjs меняет состояние с помощью Stripe: меняет состояние в зависимости от компонента

Я работаю над платежной системой Stripe на Reactjs. Существует два родительских компонента CheckoutForm: каждый должен содержать форму для отдельного подписного / тарифного плана. Итак, я хочу изменить состояние объекта суммы (который создается в CheckoutForm), в зависимости от того, какой родительский компонент ->, и после этого отправить его на сервер, где производится оплата. Например: Parent1: количество: 2000; Parent2: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 ответ

Если я не понимаю вас неправильно, вы хотите использовать повторно 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>

Другие вопросы по тегам