【问题标题】:Disable button from clicking the parent element禁止按钮单击父元素
【发布时间】:2020-12-08 19:08:18
【问题描述】:

我正在构建一个 Material UI 应用。我有一个卡片组件,我需要让它可点击。但是右上角还有一个按钮,可以在点击时编辑卡片。问题是,当我点击那个按钮时,它会处理两个动作:

  • 按钮本身调用的编辑操作
  • 点击卡片

这是一段sn-p代码:

<CardActionArea href={`/${item.name}`}>
  <Card key={index}>
    <CardHeader
      action={
        <Fab color="secondary" onClick={handleClick}>
          <EditIcon color={"primary"} />
        </Fab>
      }
    />

    <CardContent className={classes.cardContent}>
      <Avatar className={classes.avatar} alt={item.name} src={item.avatar} />
      <Typography variant="h6" color="textSecondary">
        Card description
      </Typography>
    </CardContent>
  </Card>
</CardActionArea>

我怎样才能做到这一点?

【问题讨论】:

  • 您应该创建一个最小的可重现示例(在codesandbox 上更好)
  • 将FabIcon放在卡片的可点击区域之外,并使用绝对定位将它定位到位置不是更好吗?
  • 使用handleClick(e) { e.preventDefault(); ...}
  • @ChrisG,谢谢,这正是我所需要的。您是否知道如何防止单击时出现这种悬停效果?卡片现在没有点击,但是还有悬停效果
  • 不确定;你尝试过 Prãtéék 的建议了吗?

标签: javascript reactjs material-ui react-material


【解决方案1】:

在卡片组件中,您可以创建单击卡片和内部按钮时要运行的两个功能:

const onCardClick = () => {
  // your code here
}

const onButtonClick = () => {
  onCardClick()    
  // your code here
}

在 Card.jsx 中渲染卡片内的按钮时添加 onButtonClick 函数

<MyButton onClick={onButtonClick}

然后在你的按钮组件中,你给它一个 onClick 属性:

const MyButton = (props) => {
  <Button onClick={prop.onClick}>title</Button>
}

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 2017-05-30
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2017-01-31
    • 2011-07-08
    • 1970-01-01
    • 2011-09-16
    相关资源
    最近更新 更多