根据内容高度动态添加 React 元素

时间:2020-12-19 08:24:40

标签: javascript html reactjs dom

我有一个博客文章页面,其中有一个名为 PostContent 的组件,其中包含文章的文本。我想要实现的是根据其长度在此 PostContent 的段落之间动态添加一些内容。我将通过以 1.5 倍视口高度的距离引入上述内容来实现这一点。

我的问题是我无法计算距离。我正在使用 https://www.npmjs.com/package/html-react-parser,但我无法使用它访问 DOM 元素的 offsetHeight 属性,我想知道元素与容器元素顶部的距离。

有没有更好/替代的方法来实现我想要的?

谢谢!

假设视口高度为 100 像素,帖子内容为 2000 像素,所以我想每 200 像素(2 倍视口高度)添加一个元素。

<article>
 <p>This is the first example paragraph of 10px</p>
 <p>This is the second example paragraph of 10px</p>
  // ...
 <p>This is the twentieth example paragraph of 10px</p>
// ...
</article>

为此,我需要遍历 article 的所有段落,以便访问每个段落的 offsetHeight。这样,我就知道我离容器有多远。因此,我总是添加想要的元素 offsetHeight 是 200px 的倍数,对吗?

<article>
 <p>This is the first example paragraph of 10px</p>
 <p>This is the second example paragraph of 10px</p>
  // ...
 <p>This is the twentieth example paragraph of 10px</p>
 <!-- Here I would insert the first element,
      as it would be at 200px from the container (article).
  -->

 // .... same applies with the rest of the article ....
</article>

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,我想,你可以使用 react useRef 钩子。

const ref = useRef(null)
const [contentLength, setContentLength] = useState();

useEffect(() => {
   if (ref && ref.current) {
       const { current } = ref;
       setContentLength(current.offsetHeight);
   }
}, [ref])

return (
 <div ref={ref}>{content_here}</div>
)

这里我们将 ref 元素分配给帖子内容包装器 div。

已编辑:

import React, { useRef, useEffect } from 'react';

const paragraph = [
  'lorem ipsum dolor sit amet',
  'lorem ipsum dolor sit amet',
  'lorem ipsum dolor sit amet',
  'lorem ipsum dolor sit amet',
  'lorem ipsum dolor sit amet',
  'lorem ipsum dolor sit amet',
  'lorem ipsum dolor sit amet',
];

export function Main() {
  function Paragraph({ text, renderAdditionalElement }) {
    const ref = useRef(null);

    useEffect(() => {
      if (ref && ref.current) {
        const { offsetTop } = ref.current;
        if (offsetTop % 200 === 0) {
          renderAdditionalElement();
        }
      }
    }, [ref]);

    return <p ref={ref}>{text}</p>;
  }

  const renderAdditionalElement = () => <div />;

  return (
    <article>
      {paragraph.map(p => (
        <Paragraph text={p} renderAdditionalElement={renderAdditionalElement} />
      ))}
    </article>
  );
}
相关问题