reactjs - 有没有办法用不同的主要元素声明样式化的组件?
问题描述
我需要创建 2 个类似样式的组件,它们将共享它们的样式但使用不同的 HTML 元素。
有一种在运行时使用“as”属性()的方法,但我有一个特定的导出,我需要使用默认值,但我需要它以某种方式不使用它,因此链接样式的组件是“ styled.a" 和 StyledLink 组件为 "styled.span",我尝试执行以下操作:
export const StyledLink = styled.span(`
color: ${props => props.theme.colors.mainLinkColor};;
text-decoration: underline;
&:hover {
color: ${props => props.theme.colors.textAccent};
text-decoration: underline;
}
`);
export const Link = <StyledLink as={RRLink} />;
这显然是行不通的......那么有没有办法让链接模仿 StyledLink 样式但使用“a”标签而不是“span”?
解决方案
只需像这样导入和css
使用styled-components
:
import React from "react";
import ReactDOM from "react-dom";
import styled, { css } from 'styled-components';
const sharedStyles = css`
background-color: gold;
`;
const Div = styled.div`
${sharedStyles}
`;
const Button = styled.button`
${sharedStyles}
`;
const App = () => (
<>
<Div>Hello Div</Div>
<Button>Hello Button</Button>
</>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
推荐阅读
- c# - 没有 web.config 的 IIS 上的 Host Rest API Core
- firebase - 如何将 JSON 从云功能推送到 Firebase 实时数据库?
- amazon-web-services - 我如何使用 circleci 自动化我的 aws ecs 构建和 dockerisation
- php - Laravel 5.6 $errors 检查表单提交了吗?
- dns - 如何更改 Google 域合成记录的 TTL 值?
- ios - 在保持相同 avAudioSession 类别的同时控制 iOS 音频源音量
- c# - 忽略最顶层窗口的鼠标和键盘事件
- java - CSV 到双数组列表
- python - 如何在python中绘制双变量数据的饼图
- c# - CS1061“对象”不包含“原始文本”的定义