【问题标题】:Making a Styled component (img) behave like a button使 Styled 组件 (img) 表现得像一个按钮
【发布时间】:2021-08-03 21:30:05
【问题描述】:

我创建了一个组件,该组件看起来完全符合我的要求 - 但图标 (CollapseIcon & ExpandIcon) 需要为 tabbale,以便用户可以通过他们的键盘打开手风琴。我尝试将它们包装在一个按钮元素中,但它破坏了页面的样式。我添加了 role="button" 和 tabindex 但无济于事 - 任何人都可以提出一个好的解决方案吗?

const Accordion = styled.div`
  background-color: #e5e9eb;
  height: 87px;
  width: 612px;
  border-radius: 2px;
  border: 1px solid #27282a;
  margin-bottom: 48px;

  span {
    font-size: 14px;
    line-height: 20px;
    padding-left: 24px;
    padding-right: 24px;
    display: block;
  }
`;

const AccordionExpanded = styled.div`
  background-color: #e5e9eb;
  height: 174px;
  width: 612px;
  border-radius: 2px;
  border: 1px solid #27282a;
  margin-bottom: 48px;

  span {
    font-size: 14px;
    line-height: 20px;
    padding-left: 24px;
    padding-right: 24px;
    display: block;
  }
`;

const Title = styled.h3`
font-size: 12px;
letter-spacing: 1px;
text-transform: uppercase;
padding-left: 24px;
padding-top: 20px;
padding-bottom: 0px;
`;

const ExpandIcon = styled.img`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
`;

const CollapseIcon = styled.img`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
-webkit-transform: rotate(180deg);
`;

const Button = styled.button`
`;

const IconButton = styled.button`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
background-color: red;
`;

const ExpandableString = ({ attribute, className }: Props) => {
  const [isExpanded, setIsExpanded] = React.useState(false);
  const fullDescription = attribute.readonlyvalue;
  const shortHeading = fullDescription.substring(0, 40) + '...';

  function toggleContent() {
    setIsExpanded(prev => !prev);
  }

  return (
    isExpanded ? 
    <AccordionExpanded className={className}>
      <Title>Goods being sent
        <CollapseIcon role="button" tabindex="0" onKeyDown={toggleContent} onClick={toggleContent} src={chevron}/>
      </Title>
      <span>{fullDescription}</span>
    </AccordionExpanded> : 
    <Accordion className={className}>
      <Title>Goods being sent
        <ExpandIcon role="button" tabindex="0" onKeyDown={toggleContent} onClick={toggleContent} src={chevron} />
      </Title>
      <span>{shortHeading}</span>
    </Accordion>
  );
};

【问题讨论】:

    标签: html css reactjs styled-components wai-aria


    【解决方案1】:

    你离答案太近了。

    Index的第一个字符要大写

    tabIndex={0}
    

    这是可供您参考的可行代码框。

    https://codesandbox.io/s/styled-components-forked-v3wy9?file=/index.js

    【讨论】:

    • tabIndex 值也可以是数字字符串。 OP 唯一的错误是 tabIndex 的情况。但这会正常工作:tabIndex="0"
    • 好东西,谢谢。当上方和下方有更多可选项卡元素时,发现卡在手风琴组件中的问题(在展开和关闭之间切换)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 2010-09-09
    • 2012-06-21
    • 2012-11-05
    • 2013-06-12
    • 1970-01-01
    相关资源
    最近更新 更多