React JS를 사용하여 재료 UI에서 전체 카드 구성 요소를 클릭할 수 있도록 만드는 방법은 무엇입니까?
리액트 프로젝트에서 머티리얼 UI Next를 사용합니다.이미지(Card Media)와 텍스트(Card Text)가 포함된 카드 구성 요소가 있습니다.텍스트 아래에 버튼도 있습니다.제 질문은...전체 카드를 클릭할 수 있게 만드는 방법즉, 사용자가 카드 텍스트, 카드 이미지 또는 버튼을 누르든 버튼에서 호출하는 onClick 이벤트가 발생합니다.
v3 업데이트 - 2018년 8월 29일
특정 CardActionArea 컴포넌트가 Material UI 버전 3.0.0에서 특별히 이 경우를 커버하기 위해 추가되었습니다.
다음 솔루션은 v1에 고착된 경우에만 사용하십시오.
필요한 것은, 카드의 상부에 있는 카드 액션(사양 참조)입니다.
웹 라이브러리용 재료 구성요소에는 카드 구성요소의 첫 번째 사용 예가 있습니다.
MUI를 구성하면 정확한 동작을 쉽게 재현할 수 있습니다.Card*
강력한 힘을 가진 요소ButtonBase
요소.실행 예는 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
.
머티리얼 UI 4.9.10에서는 이 기능이 동작합니다.
<Card>
<CardActionArea href="https://google.com">
<CardContent>
<Typography>Click me!</Typography>
</CardContent>
</CardActionArea>
</Card>
리액트 라우터를 사용하고 있는 경우는, 이것도 동작합니다.
<Card>
<CardActionArea component={RouterLink} to="/questions">
<CardContent>
<Typography>Click me!</Typography>
</CardContent>
</CardActionArea>
</Card>
또한 Link 태그를 사용하여 카드 컴포넌트 전체를 클릭할 수 있도록 하고 네비게이션도 할 수 있습니다.
import { Link } from 'react-router-dom';
function myCard() {
return (
<Link to={'/give_your_path'}>
<Card>
<Card text="This is text"/>
</Card>
</Link>
);
}
추가 가능onClick={clickFunction}
버튼과 같은 기능에 링크되어 있는 카드의 div에 접속합니다.
다음은 https://stackoverflow.com/a/50444524/192092 덕분에 도움이 된 솔루션입니다.
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>
Material Card Action Area 컴포넌트에 모든 것을 랩합니다.안에 있는 모든 것을 클릭할 수 있습니다.
<CardActionArea>
<CardMedia>
.......Image Stuff
</CardMedia>
<CardContent>
.......Content
</CardContent>
</CardActionArea>
라우팅에 NextJs를 사용하면 이 두 가지 접근법이 효과가 있었습니다.
- 를 랩하다
<CardActionArea>
(NextJS)를 사용하여<Link>
컴포넌트:
import Link from 'next/link'
<Card>
<Link href='/your-target-path' passHref>
<CardActionArea>
...
</CardActionArea>
</Link>
</Card>
- 효과를 이용하다
useRouter
클릭 시 루트를 푸시합니다.
import { useRouter } from 'next/router'
const router = useRouter()
<Card>
<CardActionArea onClick={() => {router.push('/your-target-path')}}>
...
</CardActionArea>
</Card>
이 두 번째 접근법에서는 브라우저가 URL을 인식하지 못합니다. 즉, 활동 표시줄(호버에 표시됨)이 채워지지 않습니다.
MUI 5.0에서는 CardActionArea 컴포넌트로 실행할 수 있습니다.
export default function ActionAreaCard() {
return (
<Card sx={{ maxWidth: 345 }}>
<CardActionArea>
<CardMedia
component="img"
height="140"
image="/static/images/cards/contemplative-reptile.jpg"
alt="green iguana"
/>
<CardContent>
<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>
);
}
카드에 소품만 추가하세요.
<Card
onPress = {() => {console.log('onclick')}}
style={styles.item}
status="basic"
header={(headerProps) =>
this.renderItemHeader(headerProps, item)
}>
<Text>{item.description}</Text>
</Card>
onClick 이벤트를 다음과 같이 사용합니다.
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
card: {
cursor: "pointer",
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
function App() {
const classes = useStyles();
const clickMe = (event) => {
console.log(event);
}
return (
<div className={classes.root}>
<Card className={classes.card} onClick={(event) =>
{clickMe(event)}}>
<CardContent>
<h4>test</h4>
</CardContent>
<CardActions>
<Button size="small">Learn More</Button>
</CardActions>
</Card>
</div>
);
}
export default App;
MUI5의 경우:
를 넣다.a.<Box />
후, 카드를 「이행」으로 .<a>
태그 컴포넌트
<Box component='a' href='/dashboard' sx={{ textDecoration: 'none' }}>
<Card sx={{ height: '200px', cursor: 'pointer'}}>
<CardContent>
//CardContent
</CardContent>
</Card>
</Box>
다음과 같은 스타일 추가:
- 을 장식을 제거합니다.
<a>
부착 - 카드에 원하는 높이를 지정합니다.
- 커서를 카드 위로 가져가면 포인터로 변경
언급URL : https://stackoverflow.com/questions/49007357/how-to-make-the-whole-card-component-clickable-in-material-ui-using-react-js
'programing' 카테고리의 다른 글
rspec 요청 사양에서 요청 헤더를 설정하려면 어떻게 해야 합니다. (0) | 2023.03.18 |
---|---|
스프링 부트 - 다른 시스템(eureka, zuul, 리본, nginx 등)은 무엇에 사용됩니까? (0) | 2023.03.18 |
json 데이터를 html 테이블로 변환 (0) | 2023.03.18 |
쿼리 문자열에서 매개 변수 값을 가져오려면 어떻게 해야 합니까? (0) | 2023.03.18 |
UI 선택에서 수동으로 입력한 텍스트 허용 (0) | 2023.03.18 |