为onclick事件react添加转换时间



我正在尝试为onClick-事件添加转换时间。HomeCard元素以600px的宽度开始,在按钮的onClick-事件中,它正确地变为100%的宽度。唯一的问题是我试图将转换延迟2秒,但它不起作用。在这种情况下,添加过渡时间的正确方法是什么?

function App() {
const [cardWidth, setCardWidth] = useState("600px");
const setStyle = (cardWidth) => {
setCardWidth(cardWidth);
}
const HomeCard = styled.div`
margin: 0 auto;
background-color: #fff;
text-align: center;
border-radius: 12px;
width: ${cardWidth};
transition: width 2s;
height: 600px;
`
return (
<Wrapper>
<LogoWrapper/>
<HomeCard>
<Header>Text</Header>
<CardText>Amet minim mollit non deserunt ullamco est sit aliqua dolor do amet sint</CardText>
<Button onClick={() => setStyle("100%")}>See the animation</Button>
</HomeCard>
</Wrapper>
);
}
export default App;

您可以设置transition-delayCSS属性来指定在开始转换之前等待的持续时间。

或短transition: <property> || <duration> || <timing-function> || <delay> [, ...];

有关CSS转换的更多信息


我建议为您的HomeCard元素创建类

.home-card{
width: 600px;
transition: width 2s 2s;
}
.wide{
width: 100%;
transition: width 2s 2s;
}

并在React 中有条件地添加CCD_ 5

function App() {
const [isWide, setIsWide] = useState(false);
const toggleAnimation = () => {
setIsWide(prev => !prev);
}
return (
<div className={isWide ? "home-card wide" : "home-card"}>
<button onClick={toggleAnimation}>See the animation</button>
</div>
);
}

最新更新