如何在React按钮上单击渲染组件?

时间:2017-10-16 16:47:22

标签: reactjs

我正在为项目使用React和Material UI,并且我正在实施付款方式。我基本上会支持不同类型的付款方式,并且根据用户选择的内容我想显示一个表单,一旦用户填写表单并提交表单,我想返回到我之前的观点。我有一个看起来像这样的组件:

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,然后还更新了有关付款提供商的一些详细信息。但是,我主要想要实现的是,当我点击我的按钮时,根据选择的支付提供商(意味着先前点击/选择了哪个列表),我想渲染另一个组件。任何想法如何实现它?

2 个答案:

答案 0 :(得分:4)

您可以使用条件渲染。

首先在构造函数中初始化一个变量来存储表单,然后添加一个状态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>

答案 1 :(得分:1)

只需在render方法中添加一个条件,该方法检查状态并在条件合适时呈现新组件:

render() {
    // render payment provider component for selected provider
    const {paymentProviders, indexOfClickedItem, paymentClicked} = this.state;
    const selectedPP = paymentProviders && paymentProviders[indexOfClickedItem];
    if (paymentClicked) {
        // whatever mechanism you want to use to decide
        // what to render for this payment provider...
        const ComponentToRender = selectedPP.Component;
        return (
          <ComponentToRender
            // unselects the item when the user finishes the payment
            onComplete={() => this.setState({indexOfClickedItem: -1})}
            prop1={"foo"}
          />
        );
    }

    // if nothing selected, render list
    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>
    );
}

您的onPayment函数应发出this.setState({paymentClicked: true})来触发新的渲染路径。