react-mui实现分页功能

分页加载

使用 MUI(Material-UI)库可以方便地构建一个用户列表分页功能。以下是一个简单的示例代码,其中包含了用户信息的展示,包括 Icon、性别、名字和邮箱。

import React, { useState } from 'react';
import { Grid, Typography, Container, Pagination, Avatar, makeStyles } from '@material-ui/core';
import { Email, Person } from '@material-ui/icons';

const useStyles = makeStyles((theme) => ({
  container: {
    marginTop: theme.spacing(2),
  },
  userItem: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: theme.spacing(2),
  },
  avatar: {
    marginRight: theme.spacing(2),
  },
}));

const UserListPage = () => {
  const classes = useStyles();
  const [currentPage, setCurrentPage] = useState(1);
  const usersPerPage = 10; // 每页显示的用户数量
  const users = [
    { id: 1, name: 'Alice', gender: 'Female', email: 'alice@example.com' },
    { id: 2, name: 'Bob', gender: 'Male', email: 'bob@example.com' },
    // 其他用户信息
  ];

  // 计算总页数
  const totalPages = Math.ceil(users.length / usersPerPage);

  // 处理页码变更
  const handlePageChange = (event, value) => {
    setCurrentPage(value);
  };

  // 根据当前页码和每页用户数量计算需要展示的用户列表
  const startIndex = (currentPage - 1) * usersPerPage;
  const endIndex = startIndex + usersPerPage;
  const usersToShow = users.slice(startIndex, endIndex);

  return (
    <Container className={classes.container}>
      {usersToShow.map((user) => (
        <div key={user.id} className={classes.userItem}>
          <Avatar className={classes.avatar}>
            <Person />
          </Avatar>
          <div>
            <Typography variant="body1">{user.name}</Typography>
            <Typography variant="body2">{user.gender}</Typography>
            <Typography variant="body2">
              <Email fontSize="small" /> {user.email}
            </Typography>
          </div>
        </div>
      ))}
      <Grid container justifyContent="center">
        <Pagination
          count={totalPages}
          page={currentPage}
          onChange={handlePageChange}
          variant="outlined"
          shape="rounded"
        />
      </Grid>
    </Container>
  );
};

export default UserListPage;

以上代码通过使用 MUI 的 Grid、Typography、Container、Pagination 和 Avatar 等组件来实现一个简单的用户列表分页功能,其中包含了 Icon、性别、名字和邮箱的展示。

无限滚动

使用 MUI(Material-UI)库可以很方便地实现用户列表的无限滚动(Infinite Scroll)功能。无限滚动是一种在用户滚动到页面底部时自动加载更多数据的方式,从而实现流畅的加载体验,避免一次性加载大量数据导致页面性能下降。

以下是一个简单的示例代码,使用 MUI 的 Grid、Typography、Container、IconButton 等组件,结合 React Hooks 的 useState 和 useEffect 实现用户列表的无限滚动功能。

import React, { useState, useEffect } from 'react';
import {
  Grid,
  Typography,
  Container,
  IconButton,
  CircularProgress,
  makeStyles,
} from '@material-ui/core';
import { Email, Person } from '@material-ui/icons';

const useStyles = makeStyles((theme) => ({
  container: {
    marginTop: theme.spacing(2),
  },
  userItem: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: theme.spacing(2),
  },
  avatar: {
    marginRight: theme.spacing(2),
  },
  loadingContainer: {
    textAlign: 'center',
  },
}));

const UserListInfiniteScroll = () => {
  const classes = useStyles();
  const [users, setUsers] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const usersPerPage = 10; // 每页显示的用户数量

  // 模拟异步加载用户数据
  const fetchUsers = async () => {
    setIsLoading(true);
    // 模拟异步加载用户数据
    const response = await new Promise((resolve) => setTimeout(() => resolve(getMockUsers()), 1000));
    setUsers([...users, ...response]);
    setCurrentPage(currentPage + 1);
    setIsLoading(false);
  };

  useEffect(() => {
    fetchUsers();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 模拟获取用户数据
  const getMockUsers = () => {
    const startIndex = (currentPage - 1) * usersPerPage;
    const endIndex = startIndex + usersPerPage;
    const mockUsers = [
      { id: 1, name: 'Alice', gender: 'Female', email: 'alice@example.com' },
      { id: 2, name: 'Bob', gender: 'Male', email: 'bob@example.com' },
      // 其他用户信息
    ];
    return mockUsers.slice(startIndex, endIndex);
  };

  // 处理滚动到页面底部时加载更多数据
  const handleScroll = (event) => {
    const { scrollTop, clientHeight, scrollHeight } = event.currentTarget;
    if (scrollTop + clientHeight >= scrollHeight - 20 && !isLoading) {
      fetchUsers();
    }
  };

  return (
    <Container className={classes.container} onScroll={handleScroll}>
      {users.map((user) => (
        <div key={user.id} className={classes.userItem}>
          <Grid container spacing={2} alignItems="center">
            <Grid item>
              <Person />
            </Grid>
            <Grid item>
              <Typography variant="body1">{user.name}</Typography>
              <Typography variant="body2">{user.gender}</Typography>
              <Typography variant="body2">
                <Email fontSize="small" /> {user.email}
              </Typography>
            </Grid>
			</Grid>
			</div>
			))}
			{isLoading && (
			<div className={classes.loadingContainer}>
			<CircularProgress />
			</div>
			)}
			</Container>
			);
			};
			
			export default UserListInfiniteScroll;

在上面的示例中,使用了 MUI 的 Grid 组件来布局用户列表项,使用 Typography 组件展示用户信息,使用 Container 组件作为容器,使用 IconButton 和 CircularProgress 组件展示加载状态。通过 useState 和 useEffect Hooks 来管理用户数据、加载状态以及页面滚动事件。当用户滚动到页面底部时,会触发 handleScroll 函数来加载更多用户数据,从而实现了用户列表的无限滚动功能。

需要注意的是,上面的示例代码中使用了模拟的异步加载用户数据的方式,实际项目中需要根据具体的后端 API 接口来加载真实的用户数据。同时,还需要根据具体需求对样式和逻辑进行调整和优化,例如加载状态的展示方式、滚动事件的节流处理等。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现React Native横向分页加载,可以使用FlatList组件并设置horizontal属性为true。具体步骤如下: 1. 在render方法中,使用FlatList组件,并设置horizontal属性为true,同时设置data、keyExtractor、renderItem等必要属性。 2. 在renderItem方法中,返回一个包含分页内容的组件,例如一个View或者Image等。 3. 在FlatList组件中,设置onEndReachedThreshold属性为一个小数值,表示当距离底部还有多少时触发onEndReached事件。 4. 在FlatList组件中,设置onEndReached属性为一个函数,用于在底部触发时加载更多数据。 5. 在onEndReached函数中,可以向服务器请求更多数据并更新FlatList的data属性,从而实现横向分页加载。 下面是一个简单的代码示例: ``` import React, { Component } from 'react'; import { FlatList, View, Image } from 'react-native'; class HorizontalPagination extends Component { constructor(props) { super(props); this.state = { data: [], // 初始数据为空数组 page: 1, // 初始页码为1 loading: false, // 初始状态为未加载 }; } componentDidMount() { // 初始化加载第一页数据 this.loadPage(this.state.page); } loadPage = (page) => { // 请求数据 const url = `http://example.com/api/data?page=${page}`; fetch(url) .then(response => response.json()) .then(result => { // 将新数据和旧数据合并 const data = [...this.state.data, ...result.data]; // 更新state this.setState({ data: data, page: page + 1, // 下一页 loading: false, // 加载完成 }); }) .catch(error => console.error(error)); }; renderItem = ({ item }) => { // 返回一个包含分页内容的组件 return ( <View style={{ width: 200, height: 200 }}> <Image source={{ uri: item.image }} style={{ flex: 1 }} /> </View> ); }; onEndReached = () => { // 到达底部,加载更多数据 if (!this.state.loading) { this.setState({ loading: true }, () => { this.loadPage(this.state.page); }); } }; render() { return ( <FlatList data={this.state.data} keyExtractor={(item, index) => item.id.toString()} renderItem={this.renderItem} horizontal={true} // 横向分页 onEndReachedThreshold={0.5} // 距离底部50%时触发 onEndReached={this.onEndReached} /> ); } } export default HorizontalPagination; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Calvin880828

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值