簡體   English   中英

有沒有辦法將變量從ReactJS傳遞到CSS樣式表?

[英]Is there any way to pass a variable from ReactJS to a CSS stylesheet?

我正在編寫一個包含可變數量組件的滾動代碼,因此我需要根據組件數量更改translate3d移動它的距離。 我能想到的唯一方法是以某種方式從JSX文件傳遞一個數字,但我找不到辦法做到這一點。 有沒有辦法傳遞CSS變量,或其他方式來做我想要的?

有幾個« CSS in JS »庫,允許您將keyframes添加到組件動畫中。 在JavaScript中編寫樣式時,可以直接使用組件props / states或其他常量來創建組件樣式。

以下3個庫具有關鍵幀支持(我個人一直在使用第一個):

Styled-Components( GitHub

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;
`;

魅力( GitHub

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

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»模式的閱讀

希望有所幫助! :)

雖然不完全是我原本希望的,但我確實找到了一種方法來實現這一目標。 事實證明, translate3d(100%, 0, 0)不起作用的原因是因為flexbox。 一旦從元素中刪除了它,我就可以通過在React中動態創建這些樣式來設置元素寬度和動畫時間來控制動畫的速度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM