You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Button组件无法与useContext钩子配合使用问题求助

自定义Button组件无法触发useContext主题切换的解决方案

问题出在你的自定义Button组件上:虽然Props接口继承了HTMLButtonAttributes,但你没有把外部传入的onClick(以及其他原生按钮属性)传递给组件内部的原生<button>元素,导致点击事件根本没绑定到实际的按钮上。

修复方案

修改Button.tsx,把接收到的所有原生按钮属性(包括onClick)透传给内部的<button>:

import { DetailedHTMLProps, ButtonHTMLAttributes, ReactNode, useContext } from 'react';
import { ThemeContext } from 'Layout/Layout';
import cn from 'classnames'
import styles from './Button.module.scss'

interface ButtonProps extends DetailedHTMLProps<HTMLButtonAttributes<HTMLButtonElement>, HTMLButtonElement> {
      children: ReactNode
}
 
export const Button = ({ children, className, ...rest }: ButtonProps ): JSX.Element => {
      const theme = useContext<string>(ThemeContext)

      return (
            <button
                  className={cn(styles.button, className, {
                        [styles.buttonDark]: theme === 'dark',
                        [styles.buttonLight]: theme === 'light'
                  })}
                  {...rest}
            >
                  {children}
            </button>
      )
}

修改说明

  1. 在组件参数中使用...rest接收除了children和className之外的所有原生按钮属性(比如onClick、type等)
  2. 在返回的原生<button>元素上通过{...rest}把这些属性传递下去,这样外部传入的onClick回调就会被正确绑定到按钮上

这样修改后,你的自定义Button组件就能像原生按钮一样触发主题切换逻辑了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:35:28