如何使用 React Bootstrap 和网格水平显示 3 个卡片组件?

ROH*_*K F 2 javascript reactjs react-bootstrap redux react-redux

数据库.json

{
  "products": [
    {
      "id": 1,
      "name": "Moto G5",
      "quantity": 2,
      "price": 13000
    },
    {
      "id": 2,
      "name": "Racold Geyser",
      "quantity": 3,
      "price": 6000
    },
    {
      "id": 3,
      "name": "Dell Inspiron",
      "quantity": 4,
      "price": 50000
    },
    {
      "id": 4,
      "name": "Epson Printer",
      "quantity": 1,
      "price": 9500
    },
    {
      "name": "Lenovo G50",
      "quantity": 2,
      "price": 50000,
      "id": 5
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

应用程序.js

{
  "products": [
    {
      "id": 1,
      "name": "Moto G5",
      "quantity": 2,
      "price": 13000
    },
    {
      "id": 2,
      "name": "Racold Geyser",
      "quantity": 3,
      "price": 6000
    },
    {
      "id": 3,
      "name": "Dell Inspiron",
      "quantity": 4,
      "price": 50000
    },
    {
      "id": 4,
      "name": "Epson Printer",
      "quantity": 1,
      "price": 9500
    },
    {
      "name": "Lenovo G50",
      "quantity": 2,
      "price": 50000,
      "id": 5
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

所有产品页面.js

import React from 'react';
import {BrowserRouter as Router, Route, Switch, NavLink} from 'react-router-dom';
import AllProductsPage from './components/AllProductsPage';
import AddProductPage from './components/AddProductPage';
import ProductDetail from './components/ProductDetail';
import './App.css'
import {Provider} from 'react-redux';
import configureStore from './stores/configureStore';
import {loadProduct} from './actions/productActions';

export default class App extends React.Component {
  render() {

       const About=()=>(
              <div>
                  <h1>About : This application provides information about the products </h1>
              </div>
      );

      const Header = ()=>(
        <header>
            <NavLink to="/about" activeClassName="is-active" >About</NavLink>
            <NavLink to="/" exact={true} activeClassName="is-active" >Products</NavLink>
        </header>
    );

       
      const store = configureStore();
      //loading data from db.json and into the store through the reducers
      store.dispatch(loadProduct());

      return (
        <Provider store={store}>
          <Router>
              <Header/>
              <Switch>
                <Route path="/" exact={true} component={AllProductsPage} />
                <Route path="/about"  component={About}/>
                <Route path="/addProduct" component={AddProductPage} />
                <Route path="/ProductDetail" component={ProductDetail}/>
              </Switch>
          </Router>
        </Provider>
      );
  }
}

Run Code Online (Sandbox Code Playgroud)

产品列表.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { Link } from "react-router-dom";
import ProductList from "./ProductList";
import * as productActions from "../actions/productActions";
import { Button } from "react-bootstrap";

class AllProductsPage extends Component {
  render() {
    return (
      <div>
        <h1>Product List - Using Redux</h1>
        <ProductList products={this.props.products} />
        <br />
        <Link to="/addProduct"><Button variant="primary">Add Product</Button>{" "}</Link>
      </div>
    );
  }
}

function mapStateToProps(state, ownProps) {
  return {
    products: state.products,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(productActions, dispatch),
  };
}

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

Run Code Online (Sandbox Code Playgroud)

产品.js

import React from "react";
import Product from "./Product";
import { Container, Row, Col} from "react-bootstrap";

export default class ProductList extends React.Component {
  render() {
    var productNodes = this.props.products.map((product) => {
      return (
        <Product
          key={product.id}
          id={product.id}
          name={product.name}
          quantity={product.quantity}
          price={product.price}
        >
          {product.text}
        </Product>
      );
    });
    return (
      <div>
        <Container>
          <Row>
          <Col xs="4">
                {productNodes}
              </Col>
          </Row>
        </Container>
      </div>
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

现在这是我第一次使用react-bootstrap。所以我在这里没有太多线索。

我想要的是以这样的方式生成卡片,即连续三张卡片。

现在这是我到目前为止所做的代码,但我对如何使卡片水平放置而感到困惑,而无需编写<Col>三次,这会连续重复相同的组件3次。请帮忙。

小智 6

您需要将数据分成几行,每行包含 3 列,每列包含一个产品。您可以通过使用chunk 函数来解决这个问题,该函数将一个数组和一个块大小作为参数,并输出一个包含所有块的数组。有许多库可以实现此功能(例如 lodash),但为了简单起见,只需从此处获取 chunk 函数即可。

解决方案

  1. 从知名库复制或导入块函数。
const chunk = (arr, chunkSize = 1, cache = []) => {
  const tmp = [...arr]
  if (chunkSize <= 0) return cache
  while (tmp.length) cache.push(tmp.splice(0, chunkSize))
  return cache
}
Run Code Online (Sandbox Code Playgroud)
  1. 将数据分割成固定长度的块。
const productsChunks = chunk(props.products, 3);
Run Code Online (Sandbox Code Playgroud)
  1. 将每个块渲染为包含 3 列的行,其中包含您的 Product 组件。
const rows = productsChunks.map((productChunk, index) => {
    const productsCols = productChunk.map((product, index) => {
        return (
        <Col xs="4" key={product.id}>
          <Product key={product.id} quantity={product.quantity} price={product.price} name={product.name} />      
        </Col>
      );
    });
    return <Row key={index}>{productsCols}</Row>
});
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题,让我知道您对我的解决方案的看法。为了清楚起见,我添加了一个 JSFiddle。 我的 JSFiddle:链接

  • 哇......工作得很好,我必须学习像 CHUNK 这样的新东西。多谢 (2认同)