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

问题描述

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

推荐答案

特定的,专门针对版本中的这种情况材质界面的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上的:

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组件可点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 05:00