如何在 Stitches js 组件中使用 prop 值?

Edy*_*rne 4 css reactjs stitches

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

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

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

    variants: {
        size: {
            '20': {marginBottom: '$20'}
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

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

<Spacer size={'30px'} />
Run Code Online (Sandbox Code Playgroud)

甚至更好:

<Spacer size={'$sizes$3'} />
Run Code Online (Sandbox Code Playgroud)

我如何使用这个值才能marginBottom匹配我给它的任何值?

Lea*_*ues 6

Stitches Github 上有一个关于将动态值作为属性传递的可能性的讨论。但缝合的目标是尽可能最小runTime,所以没有实现!

Github PR 缝合

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

所有缝合元素都获得该css属性,并且您可以通过它传递新属性!

样式组件:

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

成分:


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 }} />
    </>
  )
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,对于我这个问题来说,最好的解决方案是有效的。简化了代码,更有利于后期维护!