You need to enable JavaScript to run this app. React中如何将加载Spinner放置到登录按钮内部
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将加载Spinner放置到登录按钮内部

登录按钮内嵌Spinner渲染错位解答

问题根因

当前实现中Spinner跑到按钮外部的原因有两点:

  • Spinner组件的基础样式是为独立展示场景编写的,带有100px顶部外边距、70px固定宽度,完全不匹配按钮的内部空间尺度,直接将Spinner挤出按钮边界
  • React组件内错误使用原生HTML的class属性,未遵循React规范采用className写法,不仅会触发运行时警告,也可能出现样式绑定失效

修改步骤

1. 修正组件属性写法

打开ButtonLoader.js,将所有标签上的class属性替换为className,符合React语法规范:

import React from "react";
import "./styles/ButtonLoader.css";

const ButtonLoader = () => {
  return (
    <div className="spinner">
        <div className="bounce1"></div>
        <div className="bounce2"></div>
        <div className="bounce3"></div>
    </div>
  );
};

export default ButtonLoader;

2. 调整Spinner样式适配按钮场景

打开ButtonLoader.css,删除独立展示用的冗余样式,缩小尺寸适配按钮内部空间:

.spinner {
    /* 移除原100px顶部外边距,保留居中逻辑 */
    margin: 0 auto;
    /* 缩小宽度,从原70px调整到适配按钮的30px */
    width: 30px;
    text-align: center;
    /* 增加行高对齐按钮文字,避免垂直偏移 */
    line-height: 1;
}

.spinner > div {
    /* 缩小圆点尺寸,从原18px调整为8px,避免撑大按钮 */
    width: 8px;
    height: 8px;
    /* 圆点颜色继承按钮文字色,保持视觉统一 */
    background-color: currentColor;

    border-radius: 100%;
    display: inline-block;
    -webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
    animation: sk-bouncedelay 1.4s infinite ease-in-out both;
}

/* 动画延迟配置保持不变 */
.spinner .bounce1 {
    -webkit-animation-delay: -0.32s;
    animation-delay: -0.32s;
}

.spinner .bounce2 {
    -webkit-animation-delay: -0.16s;
    animation-delay: -0.16s;
}

/* 动画关键帧配置保持不变 */
@-webkit-keyframes sk-bouncedelay {
    0%, 80%, 100% { -webkit-transform: scale(0) }
    40% { -webkit-transform: scale(1.0) }
}

@keyframes sk-bouncedelay {
    0%, 80%, 100% { 
      -webkit-transform: scale(0);
      transform: scale(0);
    } 40% { 
      -webkit-transform: scale(1.0);
      transform: scale(1.0);
    }
}

3. 可选优化

原按钮内用于展示登录文案的是<h2>标题标签,自带默认上下外边距,会撑大按钮内边距,建议替换为行内标签<span>,避免样式冲突:

{/* Login.js 按钮代码片段 */}
<button onClick={this.handleFormSubmit} className="auth-form-submitBtn">
   {this.state.submitting ? <ButtonLoader /> : <span className="text">Login</span>}
</button>

内容的提问来源于stack exchange,提问作者ny195

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.19 00:06:00