多个Reactstrap按钮之间的React Toggle Active类

时间:2019-01-09 04:37:22

标签: reactjs reactstrap

我是React和Reactstrap的新手。我试图将活动类或活动属性设置为单个按钮onclick。我当前的设置同时切换所有按钮。在单击时在按钮状态之间独立切换active states的最佳方法是什么?

import React, { Component } from 'react'
import { Button } from "reactstrap";

export class Payment extends Component {
    constructor(props) {
		super(props);
		
		this.state = {
			paymentSelection: 'credit',
			active: false
		}

	}

	toggleContent = (event) => {
		const currentState = this.state.active;
		event.preventDefault();
		this.setState({
			paymentSelection: event.target.value,
			active: !currentState
		})
	}

	switchContent = (value) => {
		switch (value) {
			case 'credit':
				return <div>
					<p>Credit Content Here</p>
				</div>;
			case 'paypal':
				return <div>
					<p>PayPal Content Here</p>
				</div>;
			case 'amazon':
				return <div>
				<p>Amazon Content Here</p>
			</div>;
			case 'more':
				return <div>
				<p>More Content Here</p>
			</div>;
			default:
				return null;
		}
	}

    render() {
		const { paymentSelection } = this.state;
		const { active } = this.state;

        return (
            <div className="container-fluid payment-btn-group">
				<Button outline className={active ? 'active': null} color="secondary" value="credit" onClick={this.toggleContent} >Credit Card</Button>
				<Button outline className={active ? 'active': null} color="secondary" value="paypal" onClick={this.toggleContent} >PayPal</Button>
				<Button outline className={active ? 'active': null} color="secondary" value="amazon" onClick={this.toggleContent} >Amazon</Button>
				<Button outline className={active ? 'active': null} color="secondary" value="more" onClick={this.toggleContent} >+ More</Button>
				{this.switchContent(paymentSelection)}
            </div>
        );
    }
}

export default Payment

1 个答案:

答案 0 :(得分:2)

您可以这样设置活动班级

 className={paymentSelection ==='credit' ? 'active' : null}

您已经在选择付款状态时选择了付款方式。

Demo