首页 >web前端 >js教程 >可扩展文本组件

可扩展文本组件

WBOY
WBOY原创
2024-07-19 11:54:411121浏览

ExpandableText Components

import { Typography } from "@mui/material";
import { useEffect, useRef, useState } from "react";

interface ExpandableTextProps {
    text: string;
    extendedText: string;
    numberOfLine: number;
}

const ExpandableText: React.FC<ExpandableTextProps> = ({ text, extendedText = "Description", numberOfLine = 3 }) => {
    const [expanded, setExpanded] = useState(false);
    const [maxHeight, setMaxHeight] = useState<string | number>('none');
    const contentRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (contentRef.current) {
            setMaxHeight(expanded ? contentRef.current.scrollHeight : `${numberOfLine * 1.5}em`);
        }
    }, [expanded, numberOfLine])

    const toggleExpand = () => {
        setExpanded((prev) => !prev);
    };

    return (
        <>
            <div
                ref={contentRef}
                style={{
                    overflow: 'hidden',
                    maxHeight: maxHeight,
                    transition: 'max-height 0.3s ease-in-out',
                }}
            >
                <Typography
                    component="p"
                    sx={{
                        fontSize: 12,
                        fontWeight: 700,
                        letterSpacing: 0.5,
                        display: '-webkit-box',
                        WebkitBoxOrient: 'vertical',
                        WebkitLineClamp: expanded ? 'unset' : numberOfLine,
                        textOverflow: 'ellipsis',
                        mt: 1,
                    }}
                >
                    {text}
                </Typography>
            </div>
            <span style={{ color: "blue", cursor: "pointer" }} onClick={toggleExpand}>
                {expanded ? `Collapse ${extendedText}` : `Expand ${extendedText}`}
            </span>
        </>
    );
};


export default ExpandableText;

以上是可扩展文本组件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn