[英]How to toggle class when user selects a list item coming from api in react.s?
I'm working on an application where I render the DB results by a loop through using the map method.我正在开发一个应用程序,在该应用程序中,我通过使用 map 方法循环呈现数据库结果。 When the user clicks on each item, first it will add those id's into an array and toggle a CSS class to change the border color of a particular selected item, when the item is selected again, the border will disappear, same goes for all items rendered in the UI.当用户点击每个项目时,首先它会将这些 id 添加到一个数组中并切换 CSS class 以更改特定选定项目的边框颜色,当再次选择该项目时,边框将消失,所有项目都一样在 UI 中呈现。 Adding the id's into an array is working fine.将 id 添加到数组中工作正常。
I'm facing a problem toggling CSS style to change the border color when click on each item.单击每个项目时,我在切换 CSS 样式以更改边框颜色时遇到问题。
Here is my code to render items on DOM这是我在 DOM 上渲染项目的代码
const [selectedItems, setSelectedItems] = React.useState([])
const onClickHandler = (id) => {
if (selectedItems.indexOf(id) > -1) {
let updatedItems = selectedItems.filter(itemID => itemID !== id)
console.log(updatedItems);
setSelectedItems(updatedItems)
} else {
setSelectedItems(prevState => [...prevState, id] )
}
setOpen(true);
}
{
courses.length > 0 && courses.map(course => {
return (
<>
<CourseItem course={course} onClickHandler={onClickHandler} itemSelect={itemSelect} />
</>
)
})
}
function CourseItem({ course, onClickHandler }) {
const classes = useStyles();
return (
<>
<Col style={{ marginTop: 10 }}>
<Paper elevation={0} className={classes.card}>
<div className={classes.cardTop} style={{ backgroundImage: `url('${course.thumbnail}')`, backgroundSize: 'cover', backgroundPosition: 'center' }}>
<div style={{ padding: '8px 18px', display: 'flex', justifyContent : 'space-between' }}>
<CheckCircleIcon onClick={() => onClickHandler(course._id)} />
{/* <Typography component={"label"} variant="caption"> { course.level }</Typography> */}
<Chip label={course.level} style={{ color: '#000', backgroundColor: '#f9f9f9', fontFamily: 'regular1', position: 'relative', zIndex: 0}} variant="outlined" />
</div>
</div>
<div className={classes.cardBottom}>
<Typography> { course.moduleName }</Typography>
<Typography variant="subtitle2" component={"span"}> { course.description }</Typography>
</div>
</Paper>
</Col>
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.