如何使用React JS在Material UI中使整个Card组件可点击? [英] How to make the whole Card component clickable in Material UI using React JS?

查看:195
本文介绍了如何使用React JS在Material UI中使整个Card组件可点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React项目中使用 Material UI Next 。我有一个卡片组件,里面有一个图像(卡片媒体)和一个文本(卡片文本)。我在文本下方也有一个按钮。我的问题是..如何使整个卡片可点击?即。无论用户按下卡片文本,卡片图像还是按钮,它都应该触发我在按钮上调用的onClick事件。

Im using Material UI Next in a React project. I have the Card component which has an image(Card Media) and text(Card Text) inside it. I also have a button underneath the text. My question is..how to make the whole card clickable? ie. Whether a user presses on the card text, or the card image or the button, it should trigger the onClick event which I call on the button.

推荐答案


v3更新-2018年8月29日

特定的 CardActionArea 组件,专门针对版本中的这种情况材质界面的3.0.0

仅当您坚持使用v1时,才应使用以下解决方案。

Please use the following solution only if you are stuck with v1.

您可能想要实现的是 卡片操作(请参见规格)位于卡片的顶部。

What you probably want to achieve is a Card Action (see specification) on the top part of the card.

Web库的材料组件具有以下功能:其首次使用卡组件的示例

The Material Components for Web library has this as its first usage example for the Card Component.

您可以通过编写MUI Card * 轻松重现该确切行为强大的 ButtonBase 组件。 可以在CodeSandbox上的此处找到运行示例 https://codesandbox.io/s/q9wnzv7684

You can easily reproduce that exact behaviour by composing MUI Card* components with the mighty ButtonBase component. A running example can be found here on CodeSandbox: https://codesandbox.io/s/q9wnzv7684.

相关代码是这样的:

import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import ButtonBase from '@material-ui/core/ButtonBase';

const styles = {
  cardAction: {
    display: 'block',
    textAlign: 'initial'
  }
}

function MyCard(props) {
  return (
    <Card>
      <ButtonBase
          className={props.classes.cardAction}
          onClick={event => { ... }}
      >
        <CardMedia ... />
        <CardContent>...</CardContent>
      </ButtonBase>
    </Card>
  );
}

export default withStyles(styles)(MyCard)

我也强烈建议,将 CardActions 组件保留在 ButtonBase 之外。

Also I strongly suggest to keep the CardActions component outside of the ButtonBase.

这篇关于如何使用React JS在Material UI中使整个Card组件可点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆