首页 > 解决方案 > 样式属性中没有变量

问题描述

这很难解释,但是,事情是这样的:当我尝试进入getFadeContainerKeyFrameconst FadeContainer = ...,一切正常。另一方面,当我尝试从 style 中的属性中获取相同的 const 时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;

标签: javascriptcssreactjs

解决方案


您确定将有效的道具发送给该getFadeContainerKeyFrame功能吗?如果你console.log(animatingOut, direction)在里面getFadeContainerKeyFrame,道具是不是印出来的?


试着做:

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>

推荐阅读