【问题标题】:React expand animation read more/ less dynamic height反应扩展动画阅读更多/更少动态高度
【发布时间】:2022-01-23 15:23:36
【问题描述】:

我有展开组件,我正在尝试在切换时创建展开动画但没有成功**我不想明确元素的高度(我希望它是通用的):

export const Expand = ({ startOpen, content, initial }: Props) => {
    const [isOpen, { toggle }] = useToggle(startOpen);
    const [height, setHeight] = useState<any>(null);

    const ref = useRef<HTMLDivElement>(null);

    useEffect(() => {
      if (ref.current?.offsetHeight) setHeight(ref.current?.offsetHeight);
     }, [ref.current?.offsetHeight, isOpen]);
  return (
    <Container onClick={toggle}>
       <ContainerContent
        ref={ref}
        isOpen={isOpen}
        initial={initial}
        height={height}
        >
    {content}
   </ContainerContent>
   <Expanded>
    <Caret open={isOpen} />
   </Expanded>
  </Container>
 );
};

样式化组件:

const indentHeight = ({ height }: Props) => `height: ${height}px;`;

export const ContainerContent = styled.div`
  overflow: hidden;
  ${indentHeight}
  ${({ isOpen, initial }: Props) =>
    !isOpen &&
     css`
      display: -webkit-box;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      word-wrap: normal;
     -webkit-box-orient: vertical;
     -webkit-line-clamp: ${initial};
   `};

  transition: height 3s ease;
 `;

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    由于您无法从height: 0 转换为height: auto,您有两种可能性:

    • 为您的样式化组件提供height(因此您必须在应用到您的组件之前获取内容高度)。并添加 css 内联(以避免在内容要多次更改时生成新的类),如下所示:

    <ContainerContent style={{ height: myHeight}}>
        {content}
    </ContainerContent>
    • 使用 hack:使用 max-height 而不是 height。但是max-height 必须至少大于内容高度的最大值(否则您的内容将被剪切或覆盖容器)。我试过一次,但是当你定义一个太大的最大高度时,我觉得它有点滞后。所以我更喜欢第一种解决方案。

    【讨论】:

    猜你喜欢
    • 2020-11-21
    • 1970-01-01
    • 2010-11-19
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多