最近因为需求,需要开发一个支持文字展开折叠的功能,看了下antd的官网,给的例子只支持展开,不支持折叠,搜寻一番,找到一个Stack Overflow上的例子,传送门,根据例子修改了下。

思路:通过给Paragraph设置key,去动态的修改展示内容
代码:

import React, { PureComponent, Fragment } from 'react';
import { Typography } from 'antd';

const { Paragraph } = Typography;

export default class ParagraphExpand extends PureComponent {
  state = {
    fold: false,
    key: 0,
  };
  onExpand = () => {
    this.setState({ fold: true });
  };
  onCollapse = e => {
    e.preventDefault();
    this.setState(({ key }) => ({ fold: false, key: key + 1 }));
  };
  render() {
    const { rows = 1, content } = this.props;
    const { fold, key } = this.state;
    return (
      <Fragment>
        <div key={key}>
          <Paragraph ellipsis={{ rows, expandable: true, onExpand: this.onExpand }}>
            {content}
          </Paragraph>
        </div>
        {fold && <a href=":;" onClick={this.onCollapse}>Collapse</a>}
      </Fragment>
    );
  }
}

Moonlight
98 声望0 粉丝

你可真是个小妖精~