【问题标题】:array.map() does not render items horizontally in a grid container in Reactarray.map() 不会在 React 的网格容器中水平渲染项目
【发布时间】:2023-03-05 13:15:01
【问题描述】:

我正在使用 React 和 material-ui。 我的目标是呈现一个网格容器,从一个外部 javascript 文件开始,导出它自己的数组。此网格每行必须有 3 个项目,但目前它仅将项目呈现在单个列上。 代码如下:

import React from "react";
import CoffeeCard from "./CoffeeCard";
import { Grid } from "@material-ui/core";
import files from "./constants";

function Content() {
  return (
    <Grid direction="rows" container spacing={2}>
      <Grid item xs={12} sm={4}>
        {files.map((obj) => {
          return (
            <CoffeeCard
              title={obj.title}
              price={obj.price}
              description={obj.description}
              avatarUrl={obj.avatarUrl}
              imgSrc={obj.imgSrc}
            />
          );
        })}
      </Grid>
    </Grid>
  );
}

export default Content;

【问题讨论】:

    标签: javascript html reactjs material-ui


    【解决方案1】:

    您需要为 map 函数中的单个项目移动嵌套的 Grid 组件。现在你的代码只渲染了 1 个带有 children 的 Grid item 组件,你需要为每一行渲染一个:

     <Grid direction="rows" container spacing={2}>
        {files.map((obj) => {
          return (
            <Grid item xs={12} sm={4}>
              <CoffeeCard
                title={obj.title}
                price={obj.price}
                description={obj.description}
                avatarUrl={obj.avatarUrl}
                imgSrc={obj.imgSrc}
              />
            </Grid>
          );
        })}
      </Grid>
    </Grid>
    

    【讨论】:

      【解决方案2】:

      问题在于您如何使用 Material UI 中的 &lt;Grid /&gt; 组件。更多信息请参考its documentation on Grid

      值得注意的是,您希望您的item 包装每个单独的项目。正如你所拥有的,你有一个单独的 item 来包装你的内容。

      所以只需将您的 &lt;Grid item&gt; 移动到您的 .map 返回值中:

      import React from 'react';
      import CoffeeCard from './CoffeeCard';
      import { Grid } from '@material-ui/core';
      import files from './constants';
      
      function Content() {
        return (
          <Grid direction="rows" container spacing={2}>
            {files.map((obj) => {
              return (
                <Grid item xs={12} sm={4}>
                  <CoffeeCard
                    title={obj.title}
                    price={obj.price}
                    description={obj.description}
                    avatarUrl={obj.avatarUrl}
                    imgSrc={obj.imgSrc}
                  />
                </Grid>
              );
            })}
          </Grid>
        );
      }
      
      export default Content;
      

      【讨论】:

        猜你喜欢
        • 2019-08-14
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        • 1970-01-01
        • 2015-07-29
        相关资源
        最近更新 更多