javascript - 根据内容高度动态添加 React 元素
问题描述
我有一个博客文章页面,其中有一个名为PostContent
包含文章文本的组件。我想要实现的是PostContent
根据它的长度在它的段落之间动态添加一些内容。我将通过以 1.5 倍视口高度的距离引入上述内容来做到这一点。
我的问题是我无法计算距离。我正在使用https://www.npmjs.com/package/html-react-parser但我无法使用它访问offsetHeight
DOM 元素的属性,我想知道元素与顶部的距离容器元素。
有没有更好/替代的方法来实现我想要的?
谢谢!
假设视口高度为 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>
解决方案
如果我正确理解了这个问题,我想,你可以使用反应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>
);
}
推荐阅读
- anaconda - Jupyter Notebook 语法高亮不工作
- kotlin - 我无法理解 Kotlin 中的 generateSequence 函数
- r - 使用“caret”包运行决策树模型时出错
- java - 如何访问 Omnikey 3121 智能卡读卡器
- firebase - Flutter 中的 Cloud Firestore getAll() 等效项
- kubernetes - 尝试从 Web 客户端 (grpc-web) 调用 GRPC 服务器(在 GKE 上)时出现“404 未找到”
- wordpress - 古腾堡自定义元块不将元保存到自定义帖子类型
- android - 如何在颤振(android)应用程序中使用 C++ 代码?
- bash - Bash函数不回显附加参数
- sql - 分层查询显示每个父级下的所有子级