備注:
- 使用
TypeScript
和React
的函數(shù)式組件語法。此組件的目的是顯示文本,如果文本內(nèi)容超出了指定的行數(shù),它將顯示一個“查看更多
”的按鈕。- 當(dāng)用戶點擊這個按鈕時,將展示全部的文本內(nèi)容。組件使用了自定義的鉤子
useBoundingClientRect
來確定是否需要顯示這個按鈕
//index.tsx文件
import type { FC, JSX } from 'react';
import { Fragment, useState } from 'react';
import type { StandardProps } from '@tarojs/components';
import { Image, Text, View } from '@tarojs/components';
import iconDropDown from '@/assets/icons/icon-dorpdown-primary.svg';
import useBoundingClientRect from '@/hooks/useBoundingClientRect';
import './index.less';
interface EllipsisProps {
rows?: number;
/**
* 收起節(jié)點
*/
foldRender?: JSX.Element;
/**
* 是否顯示收取按鈕
*/
showFold?: boolean;
/**
* 展開節(jié)點
*/
unfoldRender?: JSX.Element;
/**
* 是否顯示展開按鈕
*/
showUnfold?: boolean;
onChange?: (val: boolean) => void;
}
const Ellipsis: FC<EllipsisProps & StandardProps> = ({
rows = 1,
children,
className,
showUnfold,
unfoldRender,
}) => {
const [show, setShow] = useState(false);
const [rectAssist] = useBoundingClientRect('#rectAssist', [children]);
const [rectActual] = useBoundingClientRect('#rectActual', [children]);
const style = {
lineClamp: rows,
webkitLineClamp: rows,
};
const showMoreBtn =
!show &&
showUnfold &&
rectActual?.height &&
rectAssist?.height &&
Number(rectActual?.height) !== Number(rectAssist?.height);
return (
<Fragment>
<View
style={{ position: 'absolute', left: 0, top: -999999, opacity: 0 }}
className={className}
id="rectAssist"
>
{children}
</View>
<View
className={`lineClamp__1 ${className}`}
style={!show ? style : { display: 'block' }}
id="rectActual"
>
{children}
{!!showMoreBtn && (
<View className="unfold-wrap" id="unfoldWrap" onClick={() => setShow(true)}>
{unfoldRender || (
<View className="unfold-btn">
<Text>查看更多</Text>
<Image src={iconDropDown} />
</View>
)}
</View>
)}
</View>
</Fragment>
);
};
export default Ellipsis;
css樣式index.less文章來源:http://www.zghlxwxcb.cn/news/detail-794415.html
.lineClamp(@row) {
display: -webkit-box;
overflow: hidden;
line-clamp: @row;
-webkit-line-clamp: @row;
-webkit-box-orient: vertical;
position: relative;
}
.lineClamp__1 {
.lineClamp(1);
&::after {
color: red;
position: absolute;
right: 0;
bottom: 5px;
}
}
.lineClamp__2 {
.lineClamp(2);
}
.lineClamp__3 {
.lineClamp(3);
}
.unfold-wrap {
position: absolute;
right: 0;
bottom: 0;
display: flex;
background: linear-gradient(to left, #fff, #fff, #fff, rgba(255, 255, 255, 0.4));
}
.unfold-btn {
display: flex;
flex-direction: row;
align-items: center;
min-width: 32px;
padding: 4px 10px 4px 30px;
line-height: 1;
text {
color: #b89962;
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 12px; /* 100% */
}
image {
width: 13px;
height: 12px;
}
}
使用組件文章來源地址http://www.zghlxwxcb.cn/news/detail-794415.html
<View>
<Ellipsis className={styles.name}>{'未知文字文字文字'}</Ellipsis>
</View>
到了這里,關(guān)于省略文字,動態(tài)行,查看更多顯示全部 組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!