javascript - 仅渲染组件一次的逻辑

标签 javascript css reactjs

我需要帮助为我的 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/

相关文章:

javascript - 根据表ID获取DataTable设置

javascript - 多个复选框 - 更改消息 "Please check this box if you want to proceed"

html - 无法突出显示 <div> 和 <ul> 中的文本

html - 防止 float 图像在 div 中移动居中标题

reactjs - RTK Toolkit 如何通过 createSlice 将构建器语法与 Action 创建器一起使用?

javascript访问for in循环的计数器

html - 如何使我的页面标题响应 CSS?

reactjs - 更漂亮,eslint - classProperties 解析器插件错误

javascript - 为什么相同类型的两个组件之间共享状态?

javascript - 从 JSON 创建 html 时删除重复的 json