【问题标题】:Styled component does not apply transition effects when rerendered?重新渲染时样式化的组件不应用过渡效果?
【发布时间】:2018-01-17 14:25:37
【问题描述】:

我正在使用 styled-components 为我的组件设置动态样式,但我似乎无法让它按我想要的方式工作。

我正在尝试在以编程方式和动态聚焦的按钮上添加ease-in-out 效果。

如您所见,样式已应用,但 transition 属性没有任何效果。有没有办法做到这一点?

就像信息说明一样,组件(按钮)每 3 秒重新渲染一次以进行切换,这可能是原因吗?如果是这样如何解决这个问题?

组件

class LanguageButton extends PureComponent {
    render() {
        const { children, theme, isFocussed, ...otherProps } = this.props;

        const Button = styled.div`
            border: 1px solid ${theme};
            margin-top: 10px;
            margin-bottom: 10px;
            background-color: transparent;
            text-align: center;
            padding-top: 25px;
            padding-bottom: 25px;
            min-height: 0;
            transition: all 0.1s ease-in-out;

            :hover {
                background-color: ${theme};
                transition: all 0.1s ease-in-out;
            }
            :active {
                background-color: ${theme};
            }

            &.isFocussed {
                transition: all 0.1s ease-in-out;
                background-color: #ebebeb;

                :hover {
                    background-color: ${theme};
                    transition: all 0.1s ease-in-out;
                }
                :active {
                    background-color: ${theme};
                }
            }
        `;

        return (
            <Button
                className={classnames("BUTTON BUTTON--50 GM--noselect", { isFocussed })}
                {...otherProps}
            >
                {children}
            </Button>
        );
    }
}

【问题讨论】:

    标签: javascript css styled-components


    【解决方案1】:

    根据此代码 sn-p 乍一看,我假设您正在添加/删除此“isFocused”类,这就是您问题的根源。使用过渡,您希望避免添加/删除类本身,因为过渡无法正确呈现,因为它一开始就不存在。

    【讨论】:

    • 感谢您的浏览,否则我怎么能做到这一点?除了添加/删除一个类之外,我真的一无所知:/
    • 这取决于您要完成的工作。您正在更改按钮悬停时的背景颜色、isFocused 类的悬停等。您发生了太多冲突,这意味着您的代码只是应用了 isFocused 类的样式,因为它弹出. 另一个注意事项是您不需要在任何地方添加transition 类。只需将transition 放在您想要产生效果的根元素上,就像按钮本身一样。只需尝试在没有 isFocused 部分的情况下执行相同的代码,然后让过渡在悬停时工作。
    • 是的,确实到处都是,因为我认为这可以解决问题。但是悬停工作得很好,我认为这仅仅是因为反应正在重新渲染,所以没有发生过渡:/有什么想法吗? (实施你所说的一切后仍然无法工作)
    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2018-08-12
    • 2019-06-26
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多