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

使用@emotion/styled组件时props.style无法传递的问题求助

问题分析与解决方案

问题根源

你用styled(Layered)包装自定义组件时,Emotion会把生成的样式类名通过**className**属性传递给Layered,但你的Layered组件既没有接收这个className,也没有把它应用到内部的ComponentWrapper上。同时你错误地尝试读取props.style——这不是Emotion传递样式的默认方式,所以自然会是undefined,样式也无法生效。

解决方案一:修改自定义组件接收className

调整Layered组件,让它接收className并传递给内部的ComponentWrapper,这样Emotion生成的样式就能正确应用:

import styled from "@emotion/styled";

interface LayeredProps {
    className?: string; // 添加className属性
    [key: string]: any;
}

const Layered = ({ className, style, ...props }: LayeredProps) => {
    return (
      {/* 将className传递给内部的styled组件 */}
      <ComponentWrapper className={className} style={style}>
        <p>Hello</p>
        <p>World</p>
      </ComponentWrapper>
    )
};

export default Layered;

const ComponentWrapper = styled.div`
    display: flex;
    flex-direction: column;
`

解决方案二:直接将Layered定义为styled组件

如果不需要在Layered里做额外逻辑,推荐直接把它定义为Emotion的styled组件,这样后续扩展样式更简洁:

import styled from "@emotion/styled";

// 直接定义为styled组件
const Layered = styled.div`
    display: flex;
    flex-direction: column;
`;

export default Layered;

之后修改LayeredModified的代码不需要变更,就能正常生效:

const LayeredModified = styled(Layered)`
  margin-left: 20px !important;
  margin-right: 20px !important;
`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:01:13