react封装自定义组件

在项目中,我在不同的页面会使用相同样式的代码,为了避免写多处重复的代码,也避免后期多处维护的弊端,我们可以将相同样式的代码自定义封装成组件,在不同的页面调用自定义组件即可。

1、先封装自定义组件

1)、新建CardList文件夹

2)、在CardList文件夹里新建index.js文件,并在index.js文件里书写如下代码:

//index.js暴露组件CardList
import Card from './card';
import CardList from './cardList';

CardList.Card = Card;
export default CardList;

3)、在CardList文件夹里新建cardList.js文件,并在该文件下书写如下代码:

import { Component } from 'react';
import withRouter from 'umi/withRouter';
import style from './index.css';

/**
 * CardList组件内容
 * @param title 组件标题
 * @param extra 描述
 * @param children 内容
 * @param restProps 传入的自定义属性
 * @returns {*}
 * @constructor
 */
const CardList = ({title, extra, children, ...restProps})=>{
  return(
    <div>
      <div className={style.card2} {...restProps}>
        <nav>{title} <span className={style.details}>{extra}</span></nav>
        {React.Children.map(
          children,
          child => (child ? React.cloneElement(child, {  }) : child)
        )}
      </div>
    </div>
  )
}
export default CardList;

4)、在CardList文件夹里新建index.css文件,并在该文件里书写样式

.card2{
  height: auto;
  background-color: white;
  padding: 16px;
  border-bottom: 1px solid #ddd;
}
.card2 nav{
  color: red;
  text-align: left;
  font-family: 'Arial Normal', 'Arial';
  font-weight: 400;
  font-style: normal;
  font-size: 16px;
  color: #333333;
  margin-bottom: 0.2rem;
}
.card2 div{
  color: #999999;
  font-family: 'Arial Normal', 'Arial';
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
}
.list1{
  text-align: left;
  display: flex;
}
.list1>span{
  /*width: 50%;*/
  display: inline-block;
  vertical-align: top;
  /*white-space:nowrap;*/
  /*overflow:hidden;*/
  /*text-overflow : ellipsis;*/
  flex: 1;
}

.details{
  float: right;
  color:#2DA9FA;
}

5)、在CardList文件夹里新建card.js文件,并在该文件下书写如下代码:

import { Component } from 'react';
import withRouter from 'umi/withRouter';
import style from './index.css';

/**
 * 子组件内容
 * @param title 标题
 * @param children 内容
 * @param restProps 传入的自定义属性
 * @returns {*}
 * @constructor
 */
const Card = ({title,children,...restProps})=>{
  return(
    <div>
      <div className={style.list1} {...restProps}>
        <span>{title} {children}</span>
      </div>
    </div>
  )
}
export default Card;

6)、用法如下:

import { Component } from 'react';
import withRouter from 'umi/withRouter';
import router from 'umi/router';
import CardList from './CardList/index';
const {Card} = CardList;

class Index extends Component{
    state ={
        loading:false,
        totalList:[{"trainCount":2360,"stationName":"北京"},{"trainCount":152,"stationName":"北京东"},{"trainCount":4248,"stationName":"北京南"},{"trainCount":3336,"stationName":"北京西"},{"trainCount":56,"stationName":"通州"}],
     }

    render() {
        let info = <div>
                       {
                           this.state.totalList.map((obj,index)=>{
                               return <CardList title={`${obj.stationName}站`} extra={<span onClick={()=>{this.jump({obj})}}>查看当天数据</span>} key={index}>
                                          <Card title="当天进站列车:">{obj.trainCount||0} 车次</Card>
                                      </CardList>
                            })
                       }
                    </div>
        return (
            <div>
                {info}
            </div>
        )
    }

}
export default withRouter(Index);

7)、效果如下:

自定义组件
自定义组件

 

  • 12
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React 封装定义分页需要以下几个步骤: 1. 创建一个 Pagination 组件,该组件接收以下 props: - currentPage:当前页码 - totalPages:总页数 - onChange:页码改变回调函数 2. 在 Pagination 组件内部,通过计算得到页码列表,例如显示当前页码前后各 3 页,可以使用一个循环来生成页码列表数组。 3. 在 JSX 中渲染页码列表,并添加页码点击事件,当点击页码时,调用 onChange 回调函数,并将点击的页码传递给它。 4. 在父组件中使用 Pagination 组件,并在 onChange 回调函数中更新当前页码,例如使用 useState Hook 来保存当前页码,并在 useEffect Hook 中监听 currentPage 的变化,当 currentPage 改变时重新请求数据。 5. 在请求数据时,需要将当前页码传递给后端,例如将 currentPage 作为查询参数发送给后端 API。 下面是一个简单的 Pagination 组件实现示例: ```javascript import React, { useState, useEffect } from 'react'; function Pagination({ currentPage, totalPages, onChange }) { const [pageList, setPageList] = useState([]); useEffect(() => { const list = []; const maxPages = Math.min(totalPages, currentPage + 3); const minPages = Math.max(1, currentPage - 3); for (let i = minPages; i <= maxPages; i++) { list.push(i); } setPageList(list); }, [currentPage, totalPages]); const handleClick = (page) => { if (onChange) { onChange(page); } }; return ( <div className="pagination"> <button disabled={currentPage === 1} onClick={() => handleClick(currentPage - 1)}>Prev</button> {pageList.map((page) => ( <button key={page} className={page === currentPage ? 'active' : ''} onClick={() => handleClick(page)}>{page}</button> ))} <button disabled={currentPage === totalPages} onClick={() => handleClick(currentPage + 1)}>Next</button> </div> ); } export default Pagination; ``` 在父组件中使用 Pagination 组件: ```javascript import React, { useState, useEffect } from 'react'; import Pagination from './Pagination'; function App() { const [currentPage, setCurrentPage] = useState(1); const [totalPages, setTotalPages] = useState(1); const [data, setData] = useState([]); useEffect(() => { fetchData(); }, [currentPage]); const fetchData = async () => { const response = await fetch(`/api/data?page=${currentPage}`); const result = await response.json(); setData(result.data); setTotalPages(result.totalPages); }; const handlePageChange = (page) => { setCurrentPage(page); }; return ( <div> {data.map((item) => ( <div key={item.id}>{item.title}</div> ))} <Pagination currentPage={currentPage} totalPages={totalPages} onChange={handlePageChange} /> </div> ); } export default App; ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值