【问题标题】:Add React elements dynamically depending on the content height根据内容高度动态添加 React 元素
【发布时间】:2021-03-29 18:03:39
【问题描述】:

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

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

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

谢谢!

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

<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>

【问题讨论】:

    标签: javascript html reactjs dom


    【解决方案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>
      );
    }
    

    【讨论】:

    • 感谢您的回答,但这不是我的意思。我刚刚编辑了添加示例的问题。我希望这种方式更清楚:)
    • 嗯,我想我现在明白了:D 请检查更新的答案;)
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2011-03-31
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    相关资源
    最近更新 更多