gpt4 book ai didi

reactjs - 如何在 React 中单击按钮时渲染组件?

转载 作者:行者123 更新时间:2023-12-02 21:12:27 28 4
gpt4 key购买 nike

我正在一个项目中使用 React 和 Material UI,并且正在实现付款方式。我基本上会支持不同类型的付款方式,并且根据用户选择的类型,我想显示一个表单,一旦用户填写表单并提交,我想返回到我之前的 View 。我有一个如下所示的组件:

import React, { Component } from 'react';
import { List, ListItem } from 'material-ui';
import { Button } from '../../components';
import StripeForm from './stripe/form';
import PropTypes from 'prop-types';

class MyComp extends Component {
constructor(props) {
super(props);

this.state = {
paymentProviders: [],
indexOfClickedItem: -1,
};

this.onListItemClicked = this.onListItemClicked.bind(this);
this.onPayment = this.onPayment.bind(this);
}

onListItemClicked(paymentProvider, index) {
let paymentProviders = {
providerName: paymentProvider.ProviderName,
publicKey: paymentProvider.PublicKey,
};
this.setState({
paymentProviders: paymentProviders,
indexOfClickedItem: index,
});
}

onPayment() {
switch (this.state.paymentProviders.providerName) {
case "stripe":
// render the form for stripe payment
return ( <StripeForm /> );

case "paypal":
// render the form for paypal payment

default:
return null;
}
}

render() {
return (
<div>
<div>
<List>
{this.props.paymentProviders.map((pp, index) => {
return (
<ListItem key={pp.ProviderName}
primaryText={pp.ProviderName}
onClick={() => this.onListItemClicked(pp, index)}
/>
)
})}
</List>
</div>

<div>
<Button onClick={this.onPayment}
label="Pay" />
</div>
</div>
);
}
}

MyComp.propTypes = {
paymentProviders: PropTypes.array.isRequired,
};

export default MyComp;

因此,基本上,根据单击的 ListItem,我会更新状态中的 indexOfClickedItem,然后还会更新有关支付提供商的一些详细信息。但是,我主要想要实现的是,当单击我的按钮时,根据选择的支付提供商(意味着之前单击/选择的列表),我想渲染另一个组件。有什么想法如何实现它吗?

最佳答案

您可以使用条件渲染。

首先在构造函数中初始化一个变量来存储表单,并添加一个状态viewForm来管理是否查看表单:

constructor(props) {
super(props);

this.state = {
paymentProviders: [],
indexOfClickedItem: -1,
viewForm: false
};

this.onListItemClicked = this.onListItemClicked.bind(this);
this.onPayment = this.onPayment.bind(this);
this.paymentForm = null; //this
}

单击按钮时,在选择付款模式时有条件地为其分配一个值,并更改状态以查看表单:

    switch (this.state.paymentProviders.providerName) {
case "stripe":
this.paymentForm = <StripeForm/>
break;
case "paypal":
this.paymentForm = <PaypalForm/>
break;
default:
this.paymentForm = null;
}
this.setState({ viewForm: true });

..然后有条件地渲染它:

<div className='form-container'>
{(this.state.viewForm) ?
this.paymentForm : ''}
</div>

关于reactjs - 如何在 React 中单击按钮时渲染组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775233/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com