首页 > 解决方案 > 你如何在反应中分享风格?

问题描述

我有一个组件:

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 需要有不同的fontWeightand marginTop,等等。谁知道,将来,也许在一个地方,它可能需要 4-5 个与当前Title样式不同的字段。

我们如何解决这个问题?

方式一:

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 中处理样式。我来自一个vue.js世界。

标签: javascriptreactjsreact-native

解决方案


您应该能够在 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
  }),
);

您还必须在函数中定义道具。

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


推荐阅读