【发布时间】:2021-10-17 02:28:31
【问题描述】:
上下文:我想使用相同的 css 样式为两个不同的组件制作动画。动画依赖于传递给 AnimatedBox 组件的一些道具,例如,如果只有 props.right 为真,则仅对右边框进行动画处理。我认为css函数可以完成这项工作,所以为了不重复代码,我只创建元素并调用函数。但是,无论我做什么,我都会收到以下错误,并且组件的行为不符合预期:
Functions that are interpolated in css calls will be stringified.
这是我的一些代码(它被截断了)。
const AnimatedBox = props => (
<>
{props.absolute
?
<MaskWrapper>
<BeforeMask {...props}/>
<AfterMask {...props}/>
</MaskWrapper>
:
<AnimatedDiv {...props}></AnimatedDiv>}
</>
)
export default AnimatedBox
const commonConfig = css`
box-sizing: inherit;
position: absolute;
content: '';
border: 1px solid transparent;
border-radius: 3px;
`
const beforeConfig = css`
top: 0;
left: 0;
border-top-color: ${({top}) => `${top && "#60d75a"}`};
border-right-color: ${({right}) => `${right && "#60d75a"}`};
animation: ${expandWidth} 0.25s ease-out forwards,
${expandHeight} 0.25s ease-out 0.25s forwards;
`
const afterConfig = css`
right: 0;
bottom: 0;
animation: ${({bottom, left}) => `${
(bottom && left)
?
`
${bottomBorderColor} 0s ease-out 0.5s forwards,
${leftBorderColor} 0s ease-out 0.5s forwards,
${expandWidth} 0.25s ease-out 0.5s forwards,
${expandHeight} 0.25s ease-out 0.75s forwards;
`
: (
bottom
?
`
${bottomBorderColor} 0s ease-out 0.5s forwards,
${expandWidth} 0.25s ease-out 0.5s forwards,
${expandHeight} 0.25s ease-out 0.75s forwards;
`
: (
left
&&
`
${leftBorderColor} 0s ease-out 0.5s forwards,
${expandWidth} 0.25s ease-out 0.5s forwards,
${expandHeight} 0.25s ease-out 0.75s forwards;
`
)
)
}`
};
`
const BeforeMask = styled.div`
${beforeConfig}
`
(...)
expandWidth、expandHeight、bottomBorderColor等都是关键帧动画。我只需要知道如何编写这些函数并将它们传递给我想要的样式组件而不会出现该错误。
已解决
正如@jsejcksn 所建议的,我必须将样式化的 div 放入组件的范围内。然后我让 css 函数显式地接受参数并进行一些语法更改,然后将所需的 props 传递给它们。
const AnimatedBox = props => {
(...)
const BeforeMask = styled.div`
${beforeConfig(props.top, props.right)}
`
(...)
return (
<>
{props.absolute
?
<MaskWrapper>
<BeforeMask {...props}/>
<AfterMask {...props}/>
</MaskWrapper>
:
<AnimatedDiv {...props}></AnimatedDiv>}
</>
)}
const beforeConfig = (top, right) => css`
top: 0;
left: 0;
border-top-color: ${top && "#60d75a"};
border-right-color: ${right && "#60d75a"};
animation: ${expandWidth} 0.25s ease-out forwards,
${expandHeight} 0.25s ease-out 0.25s forwards;
`
const afterConfig = (bottom, left) => css`
right: 0;
bottom: 0;
animation: ${
(bottom && left)
?
css`
${bottomBorderColor} 0s ease-out 0.5s forwards,
${leftBorderColor} 0s ease-out 0.5s forwards,
${expandWidth} 0.25s ease-out 0.5s forwards,
${expandHeight} 0.25s ease-out 0.75s forwards;
`
:
(
bottom
?
css`
${bottomBorderColor} 0s ease-out 0.5s forwards,
${expandWidth} 0.25s ease-out 0.5s forwards,
${expandHeight} 0.25s ease-out 0.75s forwards;
`
:
(
left
&&
css`
${leftBorderColor} 0s ease-out 0.5s forwards,
${expandWidth} 0.25s ease-out 0.5s forwards,
${expandHeight} 0.25s ease-out 0.75s forwards;
`
)
)
}
`
【问题讨论】:
标签: javascript css reactjs styled-components emotion