使 Styled 组件 (img) 表现得像一个按钮

Making a Styled component (img) behave like a button

我创建了一个看起来完全符合我的要求的组件 - 但图标(CollapseIconExpandIcon)需要是 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>
  );
};

你离答案太近了。

Index首字母大写

tabIndex={0}

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

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