Making whole card clickable in Reactstrap

徘徊边缘 提交于 2020-07-21 07:29:32

问题


I'm trying to create a card that, when clicked, performs an action.

I've managed to make this work by adding a button to the card, which is bound to an event handler, and works as expected.

I'm trying to get the whole card to work with the same event handler, as opposed to using the button, but I can't seem to get this to work as I would expect.

const SiteCard = props => {
  const { site, siteSelectedCallback } = props;

  return (
    <Card onClick={siteSelectedCallback} className="card-item">
      <CardBody>
        <CardTitle>{site.name}</CardTitle>
        <CardText className="text-muted">{site.address}</CardText>
        <Button color="primary" className="float-right" value={site.id}>
         CHOOSE ME
        </Button>
      </CardBody>
    </Card>
  );
};

I've tried wrapping it in an <a> tag, but that also doesn't work.

With the example, I'd expect the card to be clickable, but actually the button still works with the event handler. I've also tried removing the button, but that doesn't make the card clickable.


回答1:


Wrapping the card with an a tag will work, though, it won't have the pointer cursor without a href which can be changed easily with CSS.

const SiteCard = ({ site, siteSelectedCallback }) => (
  <a style={{ cursor: 'pointer' }} onClick={siteSelectedCallback}>
    <Card className="card-item">
      <CardBody>
        <CardTitle>{site.name}</CardTitle>
        <CardText className="text-muted">{site.address}</CardText>
      </CardBody>
    </Card>
  </a>
);

Tested it just now with a console.log, so if that doesn't work, it's because the callback isn't working as you're expecting it to.


Another way would be to make the Card an a tag by passing a tag prop.

<Card tag="a" onClick={siteSelectedCallback} style={{ cursor: "pointer" }}>

All the options available are clearly defined in the source of the reactstrap's Card component.


I also tested with a button inside the Card without any problems.




回答2:


In case anyone arrives here for the same question, but with react-bootstrap's Card, the solution is very similar. However, instead of using the tag property, you need to use as.

<Card as="a" onClick={siteSelectedCallback} style={{ cursor: "pointer" }}>


来源:https://stackoverflow.com/questions/53973644/making-whole-card-clickable-in-reactstrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!