javascript - 你如何在反应中分享风格?
问题描述
我有一个组件:
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 需要有不同的fontWeight
and 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
世界。
解决方案
您应该能够在 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
推荐阅读
- wordpress - WPPost 错误 hasposts 函数未定义
- mysql - Power BI + MySQL - 意外错误:连接必须有效且打开
- python - 如何使用列表打印未知数量的字典键来识别键?
- avplayer - 在 Tizen TV 中前进/后退媒体时如何解决“PLAYER_ERROR_SEEK_FAILED”的问题?
- electron - 电子包装器
- yii - 迁移/向上中的异常“yii\base\UnknownPropertyException”
- karate - 加特林、空手道和经典喂食器
- string - 为什么单字母字符串有 Char 类型?
- java - 我要求它识别图像中存在的字符,我们要求它读取内容并将内容存储在变量中
- java - java - 如何在java中给出时间戳值作为参数?