如何使我的React Bootstrap卡水平排列并等距排列(如果可能的话,也要做出响应)

时间:2018-12-28 15:45:52

标签: reactjs twitter-bootstrap react-bootstrap reactstrap

我正在使用Reactstrap并动态显示我的卡片,无论我如何尝试,它们似乎都希望垂直堆叠。这是呈现它们的组件:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { CardDeck } from 'reactstrap';
import { fetchMerch } from '../actions/fetchMerchAction';
import { fetchUniqueMerch } from '../actions/fetchUniqueMerchAction';
import ItemCard from './ItemCard';
import shortid from 'shortid';

class ShopHome extends Component {

  componentDidMount() {
    this.props.onInitMerch();
  }

  showItemDetailHandler = (id) => {
    // console.log("*",id);
    this.props.onInitUniqueMerch(id);
    this.props.history.push(`detail/${this.props.id}`)
  }

  render() {

    let cards;
    if ( this.props.cards ) {
      cards = Object.values(this.props.cards).map( card => (
        <Link to={'/detail/' + card.id } key={`div-${shortid.generate()}`}>

              <ItemCard 
                key={card.id} 
                id={card.id} 
                title={card.title}
                price={card.price}
                image={card.img} 
                description={card.description}
                clicked={() => this.showItemDetailHandler(card.id)}
              />
        </Link>
        ) 
      )
    };
    return ( 
        <CardDeck>
          {cards}
        </CardDeck>     
    );
  }
}

const mapStateToProps = state => {
  // console.log("map props to state")
  // console.log("----->",state.data.cardData)
  return {
    cards: state.data.cardData,
    id: state.data.cardData
  };
}

const mapDispatchToProps = dispatch => {
  return {
    onInitMerch: () => dispatch(fetchMerch()),
    onInitUniqueMerch: (id) => dispatch(fetchUniqueMerch(id))
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(ShopHome);

这是卡的组成部分:

import React, { Component } from 'react';
import { withRouter } from 'react-router';
import { Card, CardImg, CardText, CardBody,
  CardTitle, CardSubtitle } from 'reactstrap';
import './ItemCard.css';

class ItemCard extends Component {

  render() {

    return (
    <div>
      <Card className="card-style" onClick={this.props.clicked}>
        <CardImg top width="100%" src={this.props.image} alt="Card image cap" />
        <CardBody>
          <CardTitle >{this.props.title}</CardTitle>
          <CardSubtitle>${this.props.price}</CardSubtitle>
          <CardText>{this.props.description}</CardText>
        </CardBody>
      </Card>
    </div>
    );
  }
}

export default withRouter(ItemCard);

这是ItemCard.css:

.card-style {
  max-width: 30%;
}

如果我使用直插式样式给卡片定尺寸:style = {{width:20 +'rem'}}卡片水平排列,但无法在页面上居中。他们向左对齐。我只想要三张卡片居中并均匀分布。

1 个答案:

答案 0 :(得分:1)

您可以在CardDeck上使用style={{display: 'flex', flexDirection: 'row'}},然后将style={{flex: 1}}放在卡片上。

他们应该填满剩余的空间。一件事是确保提供您想要CardDeck的大小。

有关Flexbox here

的更多信息