有几个« JS 中的 CSS » https://github.com/MicheleBertoli/css-in-js允许您添加的库keyframes
到你的组件动画。当您在 JavaScript 中编写样式时,您可以直接使用组件 props/states 或其他一些常量来创建组件样式。
以下 3 个库具有关键帧支持(我个人一直在使用第一个):
样式组件 (GitHub https://github.com/styled-components/styled-components)
import styled, { keyframes } from 'styled-components';
const rotate360 = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
const Rotate = styled.div`
display: inline-block;
animation: ${rotate360} 2s linear infinite;
`;
Glamor (GitHub https://github.com/threepointone/glamor)
import { css } from 'glamor'
let bounce = css.keyframes('bounce', {
'0%': { transform: 'scale(0.1)', opacity: 0 },
'60%': { transform: 'scale(1.2)', opacity: 1 },
'100%': { transform: 'scale(1)' }
})
<div {...css({
animation: `${bounce} 2s`,
width: 50, height: 50,
backgroundColor: 'red'
})}>
bounce!
</div>
阿佛洛狄忒(GitHub https://github.com/Khan/aphrodite)
const translateKeyframes = {
'0%': { transform: 'translateX(0)' },
'50%': { transform: 'translateX(100px)' },
'100%': { transform: 'translateX(0)' },
};
const opacityKeyframes = {
'from': { opacity: 0 },
'to': { opacity: 1 }
};
const styles = StyleSheet.create({
zippyHeader: {
animationName: [translateKeyframes, opacityKeyframes],
animationDuration: '3s, 1200ms',
animationIterationCount: 'infinite',
},
});
<div className={css(styles.zippyHeader)}>...</div>
更多关于“CSS in JS”模式的阅读
-
React:JS 中的 CSS(由 Facebook 的 Christopher Chedeau 演示) https://speakerdeck.com/vjeux/react-css-in-js(2014 年 11 月 8 日)
-
用 JS 编写样式 ≠ 编写内联样式 http://mxstbr.blog/2016/11/inline-styles-vs-css-in-js/(2016 年 11 月 25 日)
希望有帮助! :)