首页 > 解决方案 > 根据内容高度动态添加 React 元素

问题描述

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

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

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

谢谢!

假设视口高度为 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>

为此,我需要遍历 the 的所有段落,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>

标签: javascripthtmlreactjsdom

解决方案


如果我正确理解了这个问题,我想,你可以使用反应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>
  );
}

推荐阅读