【问题标题】:Generate items into galley将项目生成到厨房
【发布时间】:2021-11-17 07:24:57
【问题描述】:

我在 Typescript 中实现了这个 React Material-UI 组件:

<Grid container direction="row" justifyContent="flex-start" alignItems="flex-start">
                <Grid item xs={5}>
                    <Box m={5} pl={10}>
                        ...... some body text..........
                    </Box>
                </Grid>
            </Grid>

如果列表太大,我如何从一个数组中生成多个Grid item 并添加一个水平滚动条来列出它们?

【问题讨论】:

  • 显示的代码是“Grid item”的主体还是代码中的“Grid item”?
  • “网格项”是该代码中的内容。

标签: javascript css reactjs typescript material-ui


【解决方案1】:

您可以使用map 方法为数组的每个元素呈现一个组件。至于水平滚动,有几种方法可以做到这一点,但我发现一种行之有效的方法是将项目放置在 flex-box 容器中,然后将该容器放入另一个水平滚动的容器中。同样使用这种方法,您需要在行组件上设置width: fit-content,以便它在父组件之外展开。

假设您的数据存储在一个名为items 的数组中,每个数组的组件是GridItem。然后我们可以这样做:

function App() {
  const items = [{name: "One"}, {name: "Two"}, {name: "Three"}, {name: "Four"}, {name: "Five"}, {name: "Six"}];
  
  return (
    <div className="scroll-wrapper">
      <div className="row">
        {items.map(e => <GridItem name={e.name}/>)}
      </div>
    </div>
  )
}

function GridItem({ name }) {
  return (
    <div className="grid-item">
      {name}
    </div>
  )
}

ReactDOM.render(<App/>, document.querySelector("#root"));
.scroll-wrapper {
  overflow-x: scroll;
  padding-bottom: 1rem; /* for the scroll bar */
}

.row {
  display: flex;
  flex-direction: row;
  width: fit-content;
}

.grid-item {
  width: 30vw;
  padding: 0.25rem 0.5rem;
  border: 1px solid black;
  margin-right: 1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="root"/>

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多