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

React+styled-components传入页面类型props动态应用对应样式报错求助

问题修复方案

你的代码存在3处核心错误,按以下方式修改即可实现需求:

错误原因

  • gridTemplateAreas 语法不符合规范:grid模板区域的每行需要用独立字符串声明,原写法'header''body'属于无效JS语法,同时无法被CSS识别。
  • 带单位的CSS属性值未用字符串包裹:30px、calc(100vh - 100px)这类包含特殊符号的CSS值需要作为字符串书写,否则JS会当成表达式执行抛出错误。
  • styled组件属性取值逻辑错误:你将样式数据嵌套在名为props的字段中传给Box组件,样式回调中直接取props.xxx无法拿到对应值,需要通过props.props.xxx才能读取,这种写法也不推荐。

修正后完整代码

import React from "react";
import styled from "styled-components";

type Props = {
  type: "home" | "group";
};

// 定义Box组件的props类型,替换any更符合TS规范
type BoxStyleProps = {
  gridTemplateAreas: string;
  gridTemplateRows: string;
  padding: number;
};

export const Body: React.FC<Props> = ({ children, type }) => {
  const dataList = {
    home: {
      gridTemplateAreas: `"header" "body"`,
      gridTemplateRows: "30px calc(100vh - 100px)",
      padding: 30
    },
    group: {
      gridTemplateAreas: `"header" "menu" "body"`,
      gridTemplateRows: "30px calc(100vh - 70px)",
      padding: 30
    }
  };
  const styleData = dataList[type];
  // 直接展开样式属性传给Box,无需套一层props字段
  return <Box {...styleData}>{children}</Box>;
};

const Box = styled.div<BoxStyleProps>`
  display: grid;
  grid-template-areas: ${(props) => props.gridTemplateAreas};
  grid-template-rows: ${(props) => props.gridTemplateRows};
  padding-left: ${(props) => props.padding}px;
`;

修改说明

  • 修正了dataList内所有CSS属性值的格式,符合JS和CSS的语法要求
  • 取消了嵌套的props字段,直接将样式属性透传给Box组件,取值逻辑更清晰
  • 补充了明确的TypeScript类型定义,避免any带来的类型隐患
  • 给padding值补了px单位,避免样式不生效的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:54:03