我需要帮助为我的 React 组件创建逻辑。如果分隔线在页面上出现一次,则不应再次呈现。
因此,如果我将组件添加到页面,它就会对下面的文本进行样式设置。但是,如果我尝试再次将组件添加到页面,则应忽略分隔线/样式。我应该只能添加一次
这是我的代码:
import React from 'react';
const Divider = () => (
<>
<hr className="divider"/>
</>
);
/* Seperate css file */
hr.divider {
height: 0;
border: 0;
border-top: solid 1px #cdcdcd;
}
hr.divider ~ p.story-text {
font-size: 0.90rem;
font-weight: normal;
font-stretch: normal;
font-style: normal;
letter-spacing: normal;
line-height: 1.75rem;
color:#707174;
@include text-styles(.75rem, 1.75em, "Gordita");
@include breakpoint(tablet) {
@include text-styles(.90rem, 2em, "Gordita");
}
}
hr.divider ~ p.story-text:last-of-type {
border-top: solid 1px red;
}
最佳答案
需要使用ReactJS提供的组件LifeCycle工具。 ComponenDidMount()
加载类时仅加载一次,但 render()
用户或应用程序的每个操作都会调用该函数。这是 ReactJS 文档的链接,告诉您如何使用 ComponentDidMount()
: https://reactjs.org/docs/react-component.html#componentdidmount
关于javascript - 仅渲染组件一次的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60143548/