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

如何为Styled-components组件传递属性?Cursor组件传参报错

解决Styled-components传递自定义props的类型错误

问题分析

你在给自定义Cursor组件传递locate属性时触发类型错误,报错提示无匹配重载。核心原因是你定义的Props接口仅包含自定义的locate属性,但styled.div生成的组件本身需要兼容HTML div元素的所有固有属性,两者类型未合并导致不兼容。

解决方案

调整Props接口,让它继承React中div元素的属性类型,实现自定义属性与原生属性的兼容:

修改后的完整代码

import React, { useState, useContext } from 'react';
import styled, { ThemeProvider } from 'styled-components';
import { UserThemeContext } from './your-context-path'; // 替换为实际文件路径
import dark from './dark-theme'; // 替换为实际文件路径
import light from './light-theme'; // 替换为实际文件路径
import Home from './Home';
import GlobalStyle from './GlobalStyle';

export default function App() {
  const { theme } = useContext(UserThemeContext);
  const [locate, setLocate] = useState({ x: 0, y: 0 });

  const handleMoveMouse = (event: React.MouseEvent) => {
    event.preventDefault();
    setLocate({ x: event.pageX, y: event.pageY });
  };

  return (
    <ThemeProvider theme={theme ? dark : light}>
      <div onMouseMove={handleMoveMouse}>
        <Cursor locate={locate} />
        <Home />
        <GlobalStyle />
      </div>
    </ThemeProvider>
  );
}

// 让自定义Props继承div元素的所有原生属性类型
interface Props extends React.HTMLAttributes<HTMLDivElement> {
  locate: {
    x: number;
    y: number;
  };
}

export const Cursor = styled.div.attrs<Props>((props) => ({
  style: {
    left: `${props.locate.x - 20}px`,
    top: `${props.locate.y - 20}px`,
  },
}))`
  z-index: 9999;
  position: fixed;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  pointer-events: none;
  background: #70aca812;
  box-shadow: 0 0 150px #bdf6ff;
`;

关键说明

  • 通过extends React.HTMLAttributes<HTMLDivElement>,让自定义Props包含div元素的所有原生属性,彻底解决类型不匹配问题。
  • 同时将handleMoveMouse的参数类型改为React.MouseEvent,这是React封装的鼠标事件类型,更贴合React开发场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:51:20