业务需要实现一个文章列表,在超过3行的文字默认收起,点击展开可查看更多。
- 封装为组件 text为展开该村,rows为默认行数
- 结合useSize 获取当前文本区高度,当大于所设定的行数对应行高,则显示展开,其它小于些条件默认无展开
- visible判断展开/收起
import React, { useState, useEffect, useRef } from 'react';
import { Typography } from 'antd';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { useSize } from 'ahooks';
interface TextProps {
text: string;
rows?: number;
}
const { Paragraph } = Typography;
const TextMore: React.FC<TextProps> = ({ text, rows = 3 }) => {
const [visible, setVisible] = useState(false);
const ref = useRef(null);
const size = useSize(ref);
return (
<div style={{ position: 'relative', marginRight: 48 }}>
<Paragraph
ellipsis={
visible
? false
: {
rows: rows,
expandable: true,
symbol: (
<a style={{ visibility: 'hidden' }}>
<DownOutlined />
展开
</a>
),
}
}
ref={ref}
>
{text}
{visible && (
<a onClick={() => setVisible(false)} style={{ marginLeft: 2 }}>
<UpOutlined />
收起
</a>
)}
</Paragraph>
{/* 默认情况判断下高度 */}
{!visible && size?.height >= 66 && (
<div style={{ position: 'absolute', bottom: 0, right: 0 }}>
<a
onClick={() => {
setVisible(true);
}}
>
<DownOutlined />
展开
</a>
</div>
)}
</div>
);
};
export default TextMore;