当前位置: 首页 > 知识库问答 >
问题:

样式化组件上的Typescript和defaultProps

贺刚毅
2023-03-14

我有以下样式的组件:

import styled from "styled-components"
import { rem } from 'polished';
import theme from '../../theme';

type ButtonType = {
    intent?: keyof typeof theme.button;
};

const Button = styled.button<ButtonType>`
  border: ${({ intent }) => rem(theme.button[intent]["border-width"])} ${({ intent }) => theme.button[intent]["border-style"]} ${({ intent }) => theme.button[intent]["border-color"]};
  color: ${({ intent }) => theme.button[intent].color};
`;

Button.defaultProps = {
    intent: 'default',
};

export default Button;

其中主题是:

const intent = {
    default: '#000000',
    error: '#FF0000',
    warning: '#FF7900',
};

const theme = {
    button: {
        default: {
            'border-color': intent.default,
            'border-style': intent.default,
            'border-width': 2,
            color: intent.default,
        },
        error: {
            'border-color': intent.error,
            'border-style': intent.error,
            'border-width': 2,
            color: intent.error,
        },
        warning: {
            'border-color': intent.warning,
            'border-style': intent.warning,
            'border-width': 2,
            color: intent.warning,
        }
    }
};

export default theme;

我收到以下打字错误:

类型“未定义”不能用作索引类型。

不知道为什么假设意图是未定义的,如果它是在defaultProps中定义的-我如何让TypeScript识别这一点?

共有2个答案

琴元凯
2023-03-14

TypeScript不会接受您通过< code>Button.defaultProps定义的任何内容,因此它不“知道”它有一个默认值。相反,您可能需要直接在组件定义中设置默认值:

const Button = styled.button<ButtonType>`
  border: ${({ intent = 'default' }) => rem(theme.button[intent]["border-width"])} ${({ intent = 'default' }) => theme.button[intent]["border-style"]} ${({ intent = 'default' }) => theme.button[intent]["border-color"]};
  color: ${({ intent = 'default' }) => theme.button[intent].color};
`;
葛骏
2023-03-14

根据您对ButtonType的类型定义意图可能是未定义的。类型脚本编译器检测到这一点并为您提供所述错误。

意图设为非可选应解决此问题:

type ButtonType = {
    intent: keyof typeof theme.button;
};
 类似资料:
  • 问题内容: 这是我的样式化组件。 我收到以下警告: 我怎样才能使它工作? 问题答案: 样式化的组件将必须指定prop才能传递给类似的组件。您可以从文档中了解有关模式的更多信息 此处不是必需的,当您实际上需要从函数返回CSS时,它将作为帮助程序添加。查看条件渲染。 考虑到这些因素,该组件将变为: 一个用例

  • 问题内容: 如何在样式组件中使用条件渲染以使用React中的样式组件将按钮类设置为活动状态? 在css中,我会这样做: 在样式化的组件中,如果我尝试在类名中使用“ &&”,则不喜欢它。 问题答案: 你可以简单地做到这一点 在您的样式中,如下所示:

  • 如何在样式组件中使用条件渲染来设置我的按钮类在React中使用样式组件? 在css中,我会这样做: 如果我尝试使用'

  • 我们希望在应用程序中使用MaterialUI、next组件,在应用程序中,我们将样式化组件与SASS一起使用。为此,我们使用webpack和一个原始加载程序导入生成的CSS并应用如下样式: 我们尝试这种方法是因为样式化组件似乎是一种对react组件进行样式化的好方法,但是我们希望使用常规的sass文件,这样我们的设计师就可以像普通的一样创建样式,而不必在JS中编写CSS。 现在我面对的材料ui组件

  • 组件模版和样式 自定义组件拥有自己的 jxml 模版和 jxss 样式。 组件模版 组件模版的写法与页面模板相同。组件模版与组件数据结合后生成的节点树,将被插入到组件的引用位置上。 在组件模板中可以提供一个 <slot> 节点,用于承载组件引用时提供的子节点。 代码示例: <!-- 组件模板 --> <view class="box"> <view>组件的内部节点</view> <slot

  • 我刚刚开始尝试react native,并且正在遵循一些官方文档。 我从官方文档的样式和大小部分了解到,样式系统与css非常相似,但并不完全相同。(?) Q1:我可以只使用样式化的组件并使用“填充:20px”等,而不用担心不同类型的设备吗? 我问这个,因为文档说: React Native中的所有维度都是无单位的,表示与密度无关的像素。 此报价仅针对宽度和高度吗?。默认情况下是否有像素密度转换,或