既使用传递的道具又使用主题道具来解析样式化组件文字的最佳方法?

时间:2018-10-25 13:35:10

标签: typescript styled-components

这可行,但是看起来很人为:

import * as React from 'react';
import styled from 'styled-components';

interface StrapLineProps {
    children: any;
    variant?: 'light';
}

export default function StrapLine(props: StrapLineProps) {
    const StrapLineDiv = styled.span`
        ${providedProps => `
            ${props.variant === 'light' && `
                color: ${providedProps.theme.lightTextColor};
            `}
        `}
    `;

    return (
        <StrapLineDiv>
            {props.children}
        </StrapLineDiv>
    );
}

有没有比在Typescript项目中同时使用提供的主题道具和传递的道具更好的方法了?

这是我尝试过的替代方法,看起来更好,但会导致错误

  

[ts]参数“ providedProps”隐式具有“ any”类型。

import * as React from 'react';
import styled from 'styled-components';

interface StrapLineProps {
    children: any;
    variant?: 'light';
}

export default function StrapLine(props: StrapLineProps) {
    const StrapLineDiv = styled.span`
        ${props.variant === 'light' && `
            color: ${providedProps => providedProps.theme.lightTextColor};
        `}
    `;

    return (
        <StrapLineDiv>
            {props.children}
        </StrapLineDiv>
    );
}

这是我尝试过的另一种方法,看起来更好,但会导致错误

  

[ts]类型上不存在属性“ variant”   'ThemedStyledProps,   HTMLSpanElement>,任何>“。

import * as React from 'react';
import styled from 'styled-components';

interface StrapLineProps {
    children: any;
    variant?: 'light';
}

export default function StrapLine(props: StrapLineProps) {
    const StrapLineDiv = styled.span`
        ${providedProps => providedProps.variant === 'light' && `
            color: ${providedProps.theme.lightTextColor};
        `}
    `;

    return (
        <StrapLineDiv>
            {props.children}
        </StrapLineDiv>
    );
}

1 个答案:

答案 0 :(得分:0)

创建类是不必要的,使用Typescript,您只需在类型化的组件中传递类型道具即可:

 import styled from 'styled-components'

 interface StrapLineProps {
     children: any;
     variant?: string;
 }

 const StrapLineDiv = styled.span<StrapLineProps>`
      color: ${({variant, theme}) => variant === 'light' ? theme.lightTextColor : 'blue'};   
 `;

 StrapLineDiv.defaultProps = {
     variant: 'light'
 }

 export default StrapLineDiv

,在使用另一个文件时,您可以像这样:

AnotherFile.js

render() {
    return(
        <StrapLineDiv>
            /* What you want */
        </StrapLineDiv>
    ) 
}