2 回答
TA贡献1789条经验 获得超8个赞
通常的解决方案是让卡片传回一些识别信息或您传递给它的对象,因为您对 React 元素几乎无能为力。
如果您想要 DOM 元素,它是currentTarget您的函数接收的事件对象的属性click。
这是一个简单的示例,显示了 for 及其父级的替代品Card,在这种情况下,Card组件返回您id将其作为第二个参数传递给 click 函数:
"use strict";
const cards = Array.from(Array(5), (_, index) => ({
id: index + 1,
value: `Card ${index + 1}`
}));
function Parent() {
const click = (evt, id) => {
console.log(`evt.currentTarget.tagName = ${evt.currentTarget.tagName}, id = ${id}`);
};
return cards.map(({id, value}) =>
<Card
key={id}
value={value}
onClick={evt => click(evt, id)}
/>
);
}
function Card({value, onClick}) {
return <div onClick={onClick}>{value}</div>;
}
ReactDOM.render(<Parent />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>
TA贡献1825条经验 获得超4个赞
import React, { useRef } 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";
import Typography from "@material-ui/core/Typography";
const useStyles = makeStyles({
root: {
minWidth: 275
},
bullet: {
display: "inline-block",
margin: "0 2px",
transform: "scale(0.8)"
},
title: {
fontSize: 14
},
pos: {
marginBottom: 12
}
});
export default function OutlinedCard() {
const refs = useRef([]);
const classes = useStyles();
const click = (event) => {
const { currentTarget: { id = "" } = {} } = event;
const clickedCard = refs.current[id]; // This is the card whose button got clicked
console.log(clickedCard);
};
const createRefs = (id, node) => (refs.current[id] = node);
return (
<Card className={classes.root} variant="outlined">
<CardContent ref={(node) => {createRefs('card_1', node)}}>
<Typography>ID: '1'</Typography>
<Typography
className={classes.title}
color="textSecondary"
gutterBottom
>
Word of the Day
</Typography>
<Typography>Name: 'RAAM'</Typography>
<Typography>Blood group: 'AB+'</Typography>
<Typography>"Patient Ram is having bloodgroup AB+"</Typography>
</CardContent>
<CardActions>
<Button size="small" id="card_1" onClick={click}>
Edit
</Button>
</CardActions>
<CardContent ref={(node) => {createRefs('card_2', node)}}>
<Typography>ID: '2'</Typography>
<Typography
className={classes.title}
color="textSecondary"
gutterBottom
>
Word of the Day
</Typography>
<Typography>Name: 'RAAM'</Typography>
<Typography>Blood group: 'AB+'</Typography>
<Typography>"Patient Ram is having bloodgroup AB+"</Typography>
</CardContent>
<CardActions>
<Button size="small" id="card_2" onClick={click}>
Edit
</Button>
</CardActions>
</Card>
);
}
添加回答
举报