【问题标题】:Not getting variable in style attribute样式属性中没有变量
【发布时间】:2021-06-21 01:12:55
【问题描述】:

这很难解释,但事情是这样的:当我尝试在const FadeContainer = ... 中获取getFadeContainerKeyFrame 时,一切正常。另一方面,当我尝试从FadeContainer 中的样式属性中获取相同的常量时,它并没有……看在上帝的份上,有人可以向我解释一下吗?蒂亚!

import React, { forwardRef } from 'react'
import PropTypes from 'prop-types'
import styled, { keyframes } from 'styled-components'
import styles from '../Header.css'

const getFadeContainerKeyFrame = ({ animatingOut, direction }) => {
  if (!direction) return;
  return keyframes`
  to {
    transform: translateX(0px);
    opacity: ${animatingOut ? 0 : 1};
  }
`
}

const FadeContainer = styled.div`
  animation-name: ${getFadeContainerKeyFrame};        // <- this works ...
`

const propTypes = {
  direction: PropTypes.oneOf(["right", "left"]),
  animatingOut: PropTypes.bool,
  children: PropTypes.node
}


const FadeContents = forwardRef(
  ({ children, animatingOut, direction }, ref) => (
    <FadeContainer
      className={styles.fadeContainer}
      style={{
        animationName: getFadeContainerKeyFrame,       // <- this does not work ...
        opacity: direction && !animatingOut ? 0 : 1,
      }}
      // prevent screen readers from reading out hidden content
      aria-hidden={animatingOut}
      animatingOut={animatingOut}
      direction={direction}
      ref={ref}
    >
      {children}
    </FadeContainer>
  )
)

FadeContents.displayName = 'FadeContents'
FadeContents.propTypes = propTypes

export default FadeContents;

【问题讨论】:

  • style={{ animationName: [getFadeContainerKeyFrame], opacity: direction && !animatingOut ? 0 : 1, }} 试试这个
  • @AjayGhosh 它没有用。不过感谢您的建议!

标签: javascript css reactjs


【解决方案1】:

您确定将有效的道具发送到getFadeContainerKeyFrame 函数吗?如果你在getFadeContainerKeyFrame里面console.log(animatingOut, direction),道具打印出来了吗?


尝试做:

const getFadeContainerKeyFrame = (animatingOut, direction) => {
  if (!direction) return;
  return keyframes`
  to {
    transform: translateX(0px);
    opacity: ${animatingOut ? 0 : 1};
  }
`
}

<FadeContainer
  className={styles.fadeContainer}
  style={{
    animationName: getFadeContainerKeyFrame(animatingOut, direction)
    opacity: direction && !animatingOut ? 0 : 1,
  }}
  aria-hidden={animatingOut}
  animatingOut={animatingOut}
  direction={direction}
  ref={ref}
>
  {children}
</FadeContainer>

【讨论】:

    猜你喜欢
    • 2013-10-14
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多