我有一个列表,其中每个列表兄弟姐妹onclick淡入不同的元素与不同的文本,问题是,一次淡入开始兄弟姐妹在列表淡入效果消失,它没有再次启用。这是代码:
import { Fade, Grid, List, ListItemButton, ListItemIcon, ListItemText, Typography } from "@mui/material";
import { useEffect, useState, Fragment, forwardRef } from "react";
import { Outlet, Link } from "react-router-dom";
import {Box} from "@mui/material"
import InBoxIcon from "@mui/icons-material/Inbox";
import DraftsRounded from "@mui/icons-material/Drafts";
const MainContent = () => {
const divs = {
0: {
text: "hello",
pr: "this is pr"
},
1: {
text:"second",
pr:"this is second pr"
}
}
const [selectedItemList, setselectedItemList] = useState();
const [selectedDivList, setselectedDivList] = useState();
const [selectedElemList, setselectedElemList] = useState(false);
const handleSelectedList = ( e, index) => {
if(selectedItemList === index){ setselectedItemList() }else{setselectedItemList(index)}
setselectedDivList(divs[index]);
setselectedElemList((e) => !e);
}
const Compc = forwardRef((props, ref) => {
return(
<Box ref={ref} {...props}>
<Typography variant="h4" sx={{ textAlign: 'center' }}> {props.text} </Typography>
<Typography variant="h6" sx={{ textAlign: 'center' }}> {props.pr} </Typography>
</Box>
)
})
return (
<>
<Grid container direction="row" pt={10} pl={1} pr={1} pb={1}>
<Grid item xs={12}>
<Typography variant="h2" sx={{textAlign:'center'}}> TITLE </Typography>
</Grid>
<Grid item xs={6}>
<List aria-label="main list element">
<ListItemButton selected={selectedItemList === 0} onClick={ (e) => handleSelectedList(e, 0)}>
<ListItemIcon>
<InBoxIcon />
</ListItemIcon>
<ListItemText primary="Inbox"/>
</ListItemButton>
<ListItemButton selected={selectedItemList === 1} onClick={ (e) => handleSelectedList(e, 1)}>
<ListItemIcon>
<DraftsRounded />
</ListItemIcon>
<ListItemText primary="Drafts"/>
</ListItemButton>
</List>
</Grid>
<Grid item xs={6}>
{
selectedDivList ?
<Fade in={selectedElemList} timeout={600}>
<Compc {...selectedDivList} />
</Fade>
: ''
}
</Grid>
</Grid>
</>
)
};
export default MainContent;
如何重置用于渐变的selectedElemList,使其在单击列表中的兄弟节点时为false,并重复渐变效果
试试这两种改变。
每次点击都会显示选中的div
。
const handleSelectedList = ( e, index) => {
if(selectedItemList === index){ setselectedItemList() }else{setselectedItemList(index)}
setselectedDivList(divs[index]);
if(selectedItemList === index){ setselectedElemList((prev) => !prev); }else{setselectedElemList(true);}
}
下面的改变回答了你关于淡出效果的问题。如何在每次react组件重新渲染时触发CSS动画?
<Fade key={Math.random()} in={selectedElemList} timeout={600}>
<Compc {...selectedDivList} />
</Fade>
React在key
属性改变时重新呈现组件。通过为每次渲染提供一个随机密钥,Fade在每次点击时执行。