【问题标题】:How can i use onClick event in styled component如何在样式组件中使用 onClick 事件
【发布时间】:2021-05-07 22:09:14
【问题描述】:

我对样式有疑问。我会用图像写我的问题。我有一个图像按钮,如果我单击图像按钮,MenuItemContainer 必须是可见性的。

const MenuItemContainer = styled.div`
  visibility: hidden;
  display: inline-block;
  box-sizing: border-box;
  width: 200px;
  padding-left: 16px;
  padding-right: 16px;
  border: 1px solid ${({ theme }) => theme.palette.lightBlueGrey};
  border-radius: 5px;
  box-shadow: 0 12px 24px 0px ${({ theme }) => theme.palette.dark15};
`;

const ProfileNameWrapper = styled.div`
  display: flex;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 25px;
  background-color: ${({ theme }) => theme.palette.darkGreyBlue};
  cursor: pointer;
  justify-content: center;
  align-items: center;
  &:hover ${TooltipText} {
    visibility: visible;
  }
  &:????? ${MenuItemContainer} {
    visibility: visible;
  }
`;

我可以在这里使用 onClick 吗?

 &:????? ${MenuItemContainer} {
    visibility: visible;
  }

【问题讨论】:

  • 请不要将代码作为图片发布。而是使用“堆栈 sn-p”。确保它是minimal reproducible example
  • 图片中嵌入的文字无法搜索。这是一个社区网站,我们希望问题和答案对其他用户有用。他们将很难找到将有价值的信息锁定在图像中的问题。请更正这一点。
  • 还请您说明您在哪里使用onclick
  • 试试&:active&:target 但这不是做你想做的事的正确方法。我认为使用隐藏复选框有更好的方法。

标签: javascript css reactjs typescript styled-components


【解决方案1】:

尽管我发现在 div 上附加点击事件是错误的,但您可以利用 aria 属性破解您的问题。

const ProfileNameWrapper = styled.div`
  ...
  &:[aria-expanded='true'] ${MenuItemContainer} {
    visibility: visible;
  }
`

const Component: React.FC<Props> = (props) => {
  const [expanded, setExpanded] = React.useState(false)
  return (
     <ProfileNameWrapper onClick={() => setExpanded(!expanded)} aria-expanded={expanded} />
  )
}

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 2020-04-11
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 2021-01-12
    • 2021-05-20
    • 2017-08-05
    • 1970-01-01
    相关资源
    最近更新 更多