【问题标题】:How can a prop value be used in an Stitches js component?如何在 Stitches js 组件中使用道具值?
【发布时间】:2023-01-31 21:12:50
【问题描述】:

如何将 prop 值传递给 Stitchesjs 组件并在组件定义中使用它?

这是styled-components中的常见模式。然而,在 Stitches 中,我似乎找不到办法。以这个组件为例:

const Spacer = styled('div', {
    '16': {marginBottom: '$16'},

    variants: {
        size: {
            '20': {marginBottom: '$20'}
        }
    }
});

我不想创建 10 个变体,而是想通过道具传递数量:

<Spacer size={'30px'} />

甚至更好:

<Spacer size={'$sizes$3'} />

我怎样才能使用这个值,使 marginBottom 匹配我给它的任何东西?

【问题讨论】:

  • 据我所知,这是设计的局限性,因为它几乎没有运行时,所以它不能即时插入道具。

标签: css reactjs stitches


【解决方案1】:

看看https://stitches.dev/docs/utils

然后你可以这样使用:

<div css={{ mb: '$40' }} />

【讨论】:

    【解决方案2】:

    我一直在寻找这个答案并尝试了几种不同的方法。

    对我来说最简单的方法竟然是locally scoped theme-tokens

    所以你的样式组件看起来像这样:

    const Spacer = styled('div', {
        marginBottom: '$$marginSize',
    });
    

    然后将本地范围的令牌传递给 css 道具:

    <Spacer css={{ $$marginSize: '$sizes$3' }} />
    

    【讨论】:

    • 这行得通,但是会创建一个自定义的 css 变量,如果你通过 css 给 spacer 一个新的 prop,它会重写旧值
    【解决方案3】:

    当您需要在可以是任何值的拼接中使用 JSX 变量时,一种解决方案是使用 CSS 变量;

    所有 stitches 元素都有 css 属性,你可以通过它传递新的属性!

    样式组件:

        export const Box = styled('div', {
        marginTop: 'var(--margin-top)',
        backgroundColor: 'red',
        width: '200px',
        height: '200px',
        })
    

    成分:

    
    export function Hero({props = 200 }) {
    
      const variableExample = `${props}px`
      return (
        <>
        <Box css={{ '--margin-top': '10px' }} />
        <Box css={{ '--margin-top': '150px' }} />
        <Box css={{ '--margin-top': variableExample }} />
        </>
      )
    }
    

    到目前为止,对我来说解决这个问题的最佳解决方案!

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 2020-07-27
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 2017-06-05
      • 2023-03-14
      相关资源
      最近更新 更多