首页 > 解决方案 > 通过 props 控制组件的样式属性

问题描述

具有以下代码:

export type BreadcrumbItemProps = {
  isCurrent?: boolean;
};

const isCurrent = (props: { isCurrent?: boolean }) => props.isCurrent ? 'normal' : 'bold';

export const Item = styled.span<BreadcrumbItemProps>`
  display: inline;
  padding: 10px;
  cursor: default;
  font-weight: ${ props => isCurrent(isCurrent)};
`;

根据isCurrent我想控制字体的道具,无论是正常还是粗体,尝试这样做时出现以下错误:

const isCurrent: (props: { isCurrent?: boolean | undefined; }) => "normal" | "粗体" 类型 '(props: { isCurrent?: boolean | undefined; }) => "normal" | "bold"' 与类型 '{ isCurrent?: boolean | 没有共同的属性 不明确的; }'.ts(2559)

标签: reactjstypescriptstyled-components

解决方案


您不需要函数,您应该能够像这样内联逻辑:

export type BreadcrumbItemProps = {
  isCurrent?: boolean;
};

export const Item = styled.span<BreadcrumbItemProps>`
    display: inline;
    padding: 10px;
    cursor: default;
    font-weight: ${ props.isCurrent ? 'normal' : 'bold'};
`;

推荐阅读