首页 > 解决方案 > 如何设置包含两个 div 的可重用组件的样式,仅适用于两个父组件之一?

问题描述

我有两个不同的组件,它们看起来像列(QuantityComponentCalendarViewComponent),它们将存储不同的数据,但它们内部(每个)会有一条水平线,当时间改变时会移动(GreenCurrentTimeLine 组件),作为相同的可重用组件. 现在 greenLine 是一个单独的组件,并且在开头有一个点,但我希望该点仅用于QuantityComponent而不存在于CalendarViewComponent。GreenCurrentTimeLine组件被两个 styledComponent 分开,分别命名为:GreenLineDot。现在的问题,考虑下面的代码:

const GreenCurrentTimeLine = ({ index, hours, minutes }) => {
  // consts
  const ratio = minutes / 60; 
  const topValue = 54 * ratio; // 54 in the height of the GreenLine Div
  return (
    <>
      {index === hours && (
        <GreenLine
          index={index}
          hours={hours}
          minutes={minutes}
          style={{
            top: `${topValue}px`,
          }}
        >
          <Dot></Dot>
        </GreenLine>
      )}
    </>
  );
};
const GreenLine = styled.div`
  background-color: #02b396;
  height: 2px;
  width: 100%;
  position: absolute;
  top: 54px;
  z-index: 98;
  position: relative;
  display: flex;
  align-items: center;
`;
const Dot = styled.div`
  background-color: #02b396;
  position: absolute;
  left: 10px;
  border-radius: 20px;
  width: 10px;
  height: 10px;
  z-index: 99;
  left: -1px;
`;

我怎么说, <Dot></Dot>仅在父组件时才使用 styledComponent,在这种情况下QuantityComponent存在而不是CalendarViewComponent?我还想在CalendarViewComponent中说些什么并应用GreenCurrentTimeLine的样式,但没有,<Dot></Dot>但我不知道如何解决这个问题。我的页面的当前视图是这样的:在此处输入图像描述

我想要的是这样的:

在此处输入图像描述

标签: cssreactjsstyled-components

解决方案


由于您的组件QuantityComponentCalendarViewComponent都包含GreenCurrentTimeLine,您可以向GreenCurrentTimeLine添加一个道具以获取布尔值 showDot 并且您可以像这样动态显示或隐藏Dot组件

{ showDot && <Dot/>}

推荐阅读