【发布时间】:2021-12-07 22:17:31
【问题描述】:
假设我有一个带有简单 CSS 模块的 React 组件:
/* MyComponent.module.css */
.animatable {
background-color: red;
transition-property: background-color;
transition-duration: 500ms;
}
.animating {
background-color: grey;
}
// MyComponent.js
import styles from "./MyComponent.module.css"
const MyComponent = () => {
const [isAnimating, setIsAnimating] = useState(false)
const classes = `${styles.animatable} ${isAnimating? styles.animating : ''}`
const clickHandler = () => {
setIsAnimating(true)
setTimeout(() => setIsAnimating(false), 500)
}
return <div className={classes} onClick={clickHandler}>Click me.</div>
}
export default MyComponent
有一点代码重复,因为 CSS transition-duration 和 setTimeout() 都对持续时间进行了硬编码。
我认为有一个单一的事实来源并且它可以是 CSS 是有意义的,因为它是两个文件中“最静态的”。从 js 文件中,我可以从 CSS 模块访问 styles,但是有没有办法获取 transition-duration: 500ms 以便我可以重用它?
【问题讨论】:
-
对于这样的事情来说,这可能是一个太大的变化,但另一种方法可能是 listen for the end of the animation 并更新,而不是使用超时。
-
另一种选择是使用 CSS Custom Property (CSS Variable) 作为单一事实来源,可以在 CSS 文件和 JS 中轻松本地访问。
-
我想到了 CSS 属性方法,这可能是我想要的,它看起来更干净,更不容易出错。虽然我不知道
animationend_event,但很高兴知道!
标签: css reactjs dry css-modules