React 中的材质 UI:使 <Paper> 组件可点击

问题描述 投票:0回答:3

我想让 Paper 组件可点击。我怎样才能实现这个目标?我尝试在标签中设置一个 id 属性(如 ()),然后使用 DOM 添加事件侦听器,但它不起作用。我对如何向 Paper 组件添加点击感到困惑。 请注意,Paper 是一个 div,所以我不明白为什么我不能添加点击事件。谢谢。 我的代码:

<span>
      <Grid item xs={12} sm={12} md={6} lg={4} xl={4} spacing={5} key={something}>
        <Paper className={classes.paper} onClick={}>
             ....
        </Paper>
      </Grid>
</span>
javascript reactjs material-ui dom-events
3个回答
1
投票

尝试使用

IconButton
包裹纸质组件:

<span>
    <Grid item xs={12} sm={12} md={6} lg={4} xl={4} spacing={5} key={something}>
        <IconButton>
            <Paper className={classes.paper} onClick={}>
                 ....
            </Paper>
        </IconButton>
    </Grid>
</span>

0
投票

正如 @TigranPetrosyan 所说,它们并不打算像按钮一样显示,但您可以使用

Card
组件,它看起来与
Paper
类似,但可以点击。

<span>
  <Grid item xs={12} sm={12} md={6} lg={4} xl={4} spacing={5} key={something}>
    <Card sx={{ maxWidth: 345 }}>
      <CardActionArea>
        <CardContent onClick={() => console.log('Clicked!')}>
          <Typography gutterBottom variant="h5" component="div">
            Lizard
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Lizards are a widespread group of squamate reptiles, with over 6,000
            species, ranging across all continents except Antarctica
          </Typography>
        </CardContent>
      </CardActionArea>
    </Card>
  </Grid>
</span>

示例取自 V5 文档,我刚刚添加了

onClick
事件监听器。

Edit hardcore-panini-txq3bq


0
投票

如果您使用打字稿,您最好仔细阅读文档

现在,我们开始:

import { Paper, styled } from "@mui/material";
import { Link } from "react-router-dom";

const ClickablePaper = styled(Paper)(({theme}) => ({
  ...your styles for the Paper
})) as typeof Paper;


<ClickablePaper conponent={Link} to='/path' onClick={() => console.log('clicked')}>
  ...Paper's children
</ClickablePaper>

需要注意的事项:

  1. ...as typeof Paper
    不可忽视,否则会出现打字错误。
  2. 您还可以使用
    SX
    道具
  3. 添加样式
<ClickablePaper conponent={Link} to='/path' sx={{...your styles}} onClick={() => console.log('clicked')>
  ...Paper's children
</ClickablePaper>

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.