enter image description here

在我从数据库中获取数据并显示后,如何使它只显示4列2行和一个显示其他数据的标记.

推荐答案

若要在具有固定列数和行数的网格中显示数据,可以使用CSS网格布局.以下是如何使用CSS创建包含4列和2行的网格的示例:

.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
}

然后,您可以在容器元素上使用此CSS类,该容器元素包含要在网格中显示的数据.例如,如果您有一个要在网格中显示的数据数组,则可以使用MAP函数从该数据创建元素网格:

const data = [
  { id: 1, name: "Item 1" },
  { id: 2, name: "Item 2" },
  { id: 3, name: "Item 3" },
  { id: 4, name: "Item 4" },
  { id: 5, name: "Item 5" },
  { id: 6, name: "Item 6" },
];

function App() {
  return (
    <div className="grid">
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}

这将创建一个4列2行的网格,数据数组中的每一项都将显示在其中一个网格单元格中.

若要添加导航以显示更多数据,可以使用分页.这涉及到将数据拆分成更小的块,并且一次只显示一个块.然后,您可以添加允许用户在不同数据块之间导航的按钮或链接.

下面是一个如何在React应用程序中实现分页的示例:

function App() {
  const [currentPage, setCurrentPage] = useState(1); // Keep track of the current page
  const itemsPerPage = 4; // The number of items to display per page

  // Use the currentPage and itemsPerPage to get the slice of data to display
  const currentItems = data.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  return (
    <div>
      {/* Display the grid of items for the current page */}
      <div className="grid">
        {currentItems.map((item) => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>

      {/* Add buttons to navigate between pages */}
      <div>
        {currentPage > 1 && (
          <button onClick={() => setCurrentPage(currentPage - 1)}>
            Previous
          </button>
        )}
        {currentPage < data.length / itemsPerPage && (
          <button onClick={() => setCurrentPage(currentPage + 1)}>
            Next
          </button>
        )}
      </div>
    </div>
  );
}

在本例中,CurrentPage状态变量用于跟踪当前页面,而setCurrentPage函数用于在用户单击"上一页"时更新当前页面.

Reactjs相关问答推荐

有正确的方法来设置我的金牛座应用程序的图标吗?

值在返回页面时不更新,即使我已经更新了它们

为什么我的React App.js只在页面刷新时呈现3次?

为什么我的react虚拟化列表不显示滚动条,除非我确保高度低于rowCount*rowHeight?

React中的useEffect钩子

为什么react日历时间轴项Renderprops 不能与useState挂钩一起使用?

React 错误: 只能用作 元素的子元素,从不直接渲染.请将您的 包裹在

无法通过react 路由中的链接传递信息

无法设置 null 的属性(设置src)

react-router v6 中的 BrowserRouter 和 createBrowserRouter 有什么区别?我可以在不使用数据 API 的情况下使用 createBrowserRouter 吗?

React JS:如何判断用户使用的是浏览器 url 还是桌面 electron

如何解决在 react.js 中找不到模块错误

如何使用 UseState 正确测试组件

渲染的钩子比预期的少.这可能是由 React Hooks 中意外的提前返回语句引起的

用 scss 覆盖 MUI

您无权使用阻止 webRequest 侦听器.请务必在 list 中声明 webRequestBlocking 权限

在 Redux 中更新布尔状态时出错

运行开发服务器时如何为 Vite 指定运行时目录

下拉菜单在 AppBar 中未正确对齐

如何在按钮左下角制作 Material UI 菜单下拉菜单