【问题标题】:How to target parent component from child如何从子组件定位父组件
【发布时间】:2020-04-06 04:55:41
【问题描述】:

我有两个组件。一个Child 和一个Parent。我想在父母悬停时显示孩子

所以本质上,我正在尝试这样做:

const Child = styled.div`
  display: none;

  ${Parent}:hover & {
    display: block;
  }
`

const Parent = styled(({ className, ...props }) => {
  // Some logic

  return (
    <div className={className}>
      <ItemName />
    </div>
  );
})`
 display: flex;
 ...
`;

但是,我不能引用父级,因为父级是在子级之后声明的

我可以创建一个样式化的 div 来将这个子元素包裹在父元素中并以它为目标。即:

<Parent>
  <WrapperToTarget>
    <Child />
  </WrapperToTarget>
</Parent>

但似乎是一个糟糕的解决方法。

目前,我已经手动将一个类添加到父类并改为定位它

const Child = styled.div`
  display: none;

  parent:hover & {
    display: block;
  }
`

const Parent = styled(({ className, ...props }) => {
  return (
    <div className={classNames(className, 'parent')}>
      <ItemName />
    </div>
  );
})``

但不确定是否有“纯样式组件”的方式来做到这一点

有什么好的方法?

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    这样的东西对您的用例有用吗?

    const HoverDisplayChildrenDiv = styled.div`
      & > * {
        display: none;
      }
    
      :hover {
        cursor: pointer;
        & > * {
          display: block;
        }
      }
    `;
    

    用法:

    const Child = props => <div>Child</div>;
    
    const Parent = styled(HoverDisplayChildrenDiv)`
      background-color: lightgray;
    `;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-05
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多