繁体   English   中英

你如何在反应中分享 styles?

[英]how do you share styles in react?

我有一个组件:

const Title = styled(Typography)({
  fontFamily: 'Manrope',
  fontStyle: 'normal',
  fontWeight: 600,
  fontSize: 28,
  lineHeight: '38px',
  color: '#20232C',
  marginTop: 17,
  height: 50,
  display: 'block',
});

在这个组件中我像这样使用它..

<Title>Title here</Title>

可以想象,Title 是可以在应用程序的许多地方使用的东西。 所以我把上面的Title放在components/Titles/styles.tsx中。 然后从那里导出。

现在,无论我在哪里需要它,我都会导入Title并使用它。

问题:在其他一些地方,这个 Title 需要有不同的fontWeightmarginTop等等。 谁知道,将来,也许在一个地方,它可能需要与当前Title styles 不同的 4-5 个字段。

我们如何解决这个问题?

方式一:

export const Title = styled(Typography)(
  ({ fontWeight }: { fontWeight?: number }) => ({
    width: 'fit-content',
    fontFamily: 'Manrope',
    fontStyle: 'normal',
    fontWeight: fontWeight || 'normal',
    fontSize: 28,
    lineHeight: '25px',
    color: '#20232C',
    marginTop: '17px',
  }),
);

由于我将fontWeight可选,我们可以对所有字段执行此操作。

您如何看待这种方式以及如何处理此类情况? 这几乎是我第一次在js中处理styles。 我来自vue.js世界。

将 fontWeight 作为属性当然很好,但在进一步扩展时可能会变得过于复杂。

另一个选项是将 Title 继承到另一个样式组件中(当您找到有意义的命名用例时总是最好的),例如:

export const Subtitle = styled(Title)`
  font-size: 24px;
  font-weight: bold;
`

这是特定于样式组件的。

有两种常用方法,均在文档中介绍。

道具

const Button = styled.button` /* Adapt the colors based on primary prop */ background: ${props => props.primary? "palevioletred": "white"}; color: ${props => props.primary? "white": "palevioletred"}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; render( <div> <Button>Normal</Button> <Button primary>Primary</Button> </div> );

扩展

// The Button from the last section without the interpolations const Button = styled.button` color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; // A new component based on Button, but with some override styles const TomatoButton = styled(Button)` color: tomato; border-color: tomato; `; render( <div> <Button>Normal Button</Button> <TomatoButton>Tomato Button</TomatoButton> </div> );

您应该能够在 Title 标签中使用道具并将它们传递给单个组件,如下所示:

<Title thisTitlesHight="80px" thisTitlesWidth="50px">Title Here<Title>

然后在您的子组件中使用这些道具:

export const Title = styled(Typography)(
  ({ fontWeight }: { fontWeight?: number }) => ({
    height: this.props.thisTitlesHeight,
    width: this.props.thistitlesWidth
  }),
);

您还必须在 function 中定义道具。

我创建了一个 codeSandbox,因此您可以看到它的代码: https://codesandbox.io/s/stupefied-wildflower-wmw26?file=/src/App.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM