Sea*_*404 16 javascript css reactjs material-design material-ui
我在React项目中使用Material UI Next.我有卡组件,里面有图像(卡片介质)和文本(卡片文本).我的文字下方还有一个按钮.我的问题是..如何使整张卡片可点击?即.无论用户是否按下卡片文本,卡片图像或按钮,都应触发我在按钮上调用的onClick事件.
Pie*_*mon 23
2018年8月第3 - 29号更新
添加了一个特定的CardActionArea组件,以在Material UI 3.0.0版中特别涵盖此案例.
只有在您遇到v1时才能使用以下解决方案.
Web库的Material Components将此作为Card Component的第一个使用示例.
通过Card*使用强大的ButtonBase组件组合MUI 组件,您可以轻松地重现该确切的行为.可以在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)
Run Code Online (Sandbox Code Playgroud)
另外,我强烈建议将CardActions组件保留在外面ButtonBase.
425*_*esp 14
使用 Material UI 4.9.10,这是有效的。
<Card>
<CardActionArea href="https://google.com">
<CardContent>
<Typography>Click me!</Typography>
</CardContent>
</CardActionArea>
</Card>
Run Code Online (Sandbox Code Playgroud)
如果您使用的是反应路由器,这也有效。
<Card>
<CardActionArea component={RouterLink} to="/questions">
<CardContent>
<Typography>Click me!</Typography>
</CardContent>
</CardActionArea>
</Card>
Run Code Online (Sandbox Code Playgroud)
这是对我们有用的解决方案,感谢/sf/answers/3531116711/
import { Link as RouterLink } from 'react-router-dom'
import Link from '@material-ui/core/Link'
<Link underline='none' component={RouterLink} to='/your-target-path'>
<Card>
<CardActionArea>
...
</CardActionArea>
</Card>
</Link>
Run Code Online (Sandbox Code Playgroud)
小智 7
只需将整个内容包装在 Material CardActionArea 组件中即可。其中的所有内容都是可点击的。
<CardActionArea>
<CardMedia>
.......Image Stuff
</CardMedia>
<CardContent>
.......Content
</CardContent>
</CardActionArea>
Run Code Online (Sandbox Code Playgroud)
小智 5
我们还可以使用Link标签使整个Card组件可点击并进行导航
import { Link } from 'react-router-dom';
function myCard() {
return (
<Link to={'/give_your_path'}>
<Card>
<Card text="This is text"/>
</Card>
</Link>
);
}
Run Code Online (Sandbox Code Playgroud)