[英]How to preserve CSS transition in react child component
I'm facing this issue in which if I don't wrap an element with CSS transition into a React child component then it runs the transition smoothly and if I wrap it into a child component it doesn't show the transition at all.我正面临这个问题,如果我不将带有 CSS 过渡的元素包装到 React 子组件中,那么它会平稳地运行过渡,如果我将它包装到子组件中,它根本不会显示过渡。
App.js应用程序.js
...
const [pb, setPb] = React.useState("0");
if (pb == 0) {
setTimeout(() => {
setPb("60");
}, 1000);
}
const AnotherBall = () => {
return (
<div
className="ball2"
style={{
top: `${pb}%`
}}
></div>
);
};
return (
<div className="App">
<div
className="ball"
style={{
top: `${pb}%`
}}
></div>
<AnotherBall />
</div>
);
style.css样式.css
...
.ball,
.ball2 {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background: #ff5f5f;
border-radius: 50%;
transition: all 1s ease-in-out;
}
.ball2 {
left: 90%;
background: #ff5f5f;
}
sandbox: https://codesandbox.io/s/boring-wescoff-jcxgw?file=/src/App.js沙箱: https://codesandbox.io/s/boring-wescoff-jcxgw?file=/src/App.js
Don't declare components inside the body of other components.不要在其他组件的主体内声明组件。 Every time a component rerenders the functions it contains are redeclared, meaning they are not referentially stable from one render to the next.
每次组件重新渲染时,它所包含的函数都会被重新声明,这意味着它们在一次渲染到下一次渲染之间是不稳定的。
AnotherBall
in your example is being unmounted and remounted with the new value because React thinks it's a new component.您的示例中的
AnotherBall
正在卸载并使用新值重新安装,因为 React 认为它是一个新组件。
Instead, move the component outside of App
and pass the required value as a prop like this:相反,将组件移出
App
并将所需的值作为 prop 传递,如下所示:
// App.js
<AnotherBall pb={pb} />
// AnotherBall.js
const AnotherBall = ({pb}) => {
return (
<div
className="ball2"
style={{
top: `${pb}%`
}}
></div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.