React实现多行缩略,固定容器宽度,兼容火狐浏览器,包含展开和收起,展开和收起跟在文字末尾
时间: 2024-05-08 12:19:07 浏览: 16
1. 安装 React 和 styled-components。
```bash
npm install react styled-components
```
2. 创建一个带有多行文本的组件,并将其传递给 MultiLineEllipsis 组件。
```jsx
import React from 'react';
import MultiLineEllipsis from './MultiLineEllipsis';
const text = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla hendrerit ipsum eu ex faucibus, ac aliquet enim sagittis. Aenean efficitur dui nunc, vitae elementum magna cursus quis. Sed imperdiet arcu eu fringilla bibendum. Sed euismod, velit id sodales condimentum, nulla sapien volutpat lorem, in blandit nisl quam in dolor. Vivamus volutpat justo nec elit bibendum, non suscipit ligula malesuada.`;
const App = () => {
return (
<div style={{ width: '300px' }}>
<MultiLineEllipsis text={text} maxLines={3} />
</div>
);
};
export default App;
```
3. 创建 MultiLineEllipsis 组件。
```jsx
import React, { useState, useEffect, useRef } from 'react';
import styled from 'styled-components';
const Wrapper = styled.div`
position: relative;
line-height: ${props => props.lineHeight};
max-height: ${props => props.maxHeight};
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: ${props => props.maxLines};
`;
const Button = styled.button`
position: absolute;
right: 0;
bottom: 0;
padding: 0;
margin: 0;
border: none;
background-color: transparent;
color: blue;
cursor: pointer;
`;
const MultiLineEllipsis = ({ text, maxLines }) => {
const [isExpanded, setIsExpanded] = useState(false);
const wrapperRef = useRef(null);
const lineHeight = useRef(null);
const maxHeight = useRef(null);
useEffect(() => {
const wrapper = wrapperRef.current;
const computedStyle = window.getComputedStyle(wrapper);
lineHeight.current = computedStyle.lineHeight;
maxHeight.current = `${parseFloat(lineHeight.current) * maxLines}px`;
}, [maxLines]);
const handleClick = () => {
setIsExpanded(!isExpanded);
};
return (
<Wrapper
ref={wrapperRef}
lineHeight={lineHeight.current}
maxHeight={isExpanded ? 'none' : maxHeight.current}
maxLines={isExpanded ? 'none' : maxLines}
>
{text}
{!isExpanded && (
<Button onClick={handleClick}>
{`展开 (${text.length - 1} 字符)`}
</Button>
)}
{isExpanded && (
<Button onClick={handleClick}>
{`收起 (${text.length - 1} 字符)`}
</Button>
)}
</Wrapper>
);
};
export default MultiLineEllipsis;
```
4. 运行代码,在浏览器中查看效果。
注意,在 Firefox 浏览器中,-webkit-line-clamp 属性不起作用,需要使用 -moz-box 属性来实现多行缩略。修改 Wrapper 样式:
```jsx
const Wrapper = styled.div`
position: relative;
line-height: ${props => props.lineHeight};
max-height: ${props => props.maxHeight};
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: ${props => props.maxLines};
-moz-box-orient: vertical;
-moz-box-lines: ${props => props.maxLines};
`;
```