【问题标题】:Currying styled Template Literal function柯里化风格的模板文字函数
【发布时间】:2021-04-16 23:00:29
【问题描述】:

我试图 curry styled 函数,但 react 似乎在运行时抛出错误。 (JSX 元素没有任何构造函数或调用签名)

这个想法是创建一个可重复使用的基本样式(无需设置其附加的元素)。

const template = baseStyle`
   backgroundColor: reg
`
const Component1 = template(div)
const Component2 = template(a)

该函数接受 html 或样式组件。这是我到目前为止所做的,我很确定类型是关闭的。

export const baseStyle = (strings: TemplateStringsArray, ...rest: Interpolation<any>[]) => {
    return (element: AnyStyledComponent): StyledComponent<any, any, any, any> => {
        return styled(element)(strings, ...rest)
    }
}

有没有办法做到这一点?

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    您在这里尝试做的事情很困难,因为styled-components 的类型非常复杂。现在你的element 参数是AnyStyledComponent,这是一个已经样式化的元素。

    这种类型似乎可以工作,但请注意模板中的样式会覆盖已设置样式的组件中的样式:

    export const baseStyle = (
      strings: TemplateStringsArray,
      ...rest: Interpolation<any>[]
    ) => {
      return <C extends keyof JSX.IntrinsicElements | React.ComponentType<any>>(element: C): StyledComponent<C, any, {}, never> => {
        return styled(element)(strings, ...rest);
      };
    };
    

    使用css utility 可能会带来更好的运气。

    【讨论】:

    • 感谢 Linda,css 是一个不错的选择,我认为我现在必须使用它,事实上这可能是拥有它的确切原因。我知道应该有可能让这个工作。即使在 JS 中,我也很好奇是否有人有正确的解决方案。
    猜你喜欢
    • 2016-01-01
    • 2021-02-07
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    相关资源
    最近更新 更多