【发布时间】:2020-08-25 11:49:50
【问题描述】:
我正在构建一个 Menu/Tabs React 组件,我已将其设置为接收 SVG 和文本字符串的组合作为标题属性,以便显示为选项卡名称。
我遇到的问题是我有一个活动类,它将活动选项卡文本着色为蓝色,而不是保持黑色的 SVG。
Desired Behavior: Have active class CSS stylings applied to both text and SVG elements so that they are both blue when active and both black when they are inactive
Current Behavior: Active class stylings are applied to the text but not the SVG. When tab is active text turns blue, while the SVG remains black
这是一个演示问题的 CodeSandbox:
我的当前标签组件:
// @ts-nocheck
import React, { useState } from 'react';
import styled from '../../styles/styled';
type Props = {
children: React.ReactNode;
};
export const Tabs = (props: Props) => {
const { children } = props;
const [tab, setTab] = useState(0);
const childrenList = React.Children.toArray(children);
const tabs = childrenList.map((child, idx) => {
const title = (child as any).props.title ?? idx;
return (
<StyledTabs key={title} className={tab === idx ? 'activeTab' : ''} onClick={() => setTab(idx)}>
{title}
</StyledTabs>
);
});
const current = childrenList[tab];
return (
<div>
<div>{tabs}</div>
<div>{current}</div>
</div>
);
};
const StyledTabs = styled.button`
margin: 0 10px;
padding: 0 10px;
padding-bottom: 5px;
border: none;
background: transparent;
display: inline-block;
font-weight: 700;
text-transform: uppercase;
&.activeTab {
color: #1471da;
border-bottom: 1px solid #1471da;
outline: none;
padding-bottom: 5px;
}
`;
使用 Tabs 组件的页面:
const OverviewIcon = () => (
<svg xmlns="http://www.w3.org/2000/svg" width="35" height="35">
<path d="M0 0h16v16H0zM19 0h16v16H19zM0 19h16v16H0zM19 19h16v16H19z" />
</svg>
);
const OverviewTab = () => (
<>
<OverviewIcon />
<span>OVERVIEW</span>
</>
);
...
<Tabs>
<div title={<OverviewTab />}>
<ContentSection></ContentSection>
</div>
<div title={'ADDITIONAL CONTACTS'}>
<h1>CONTACTS</h1>
</div>
</Tabs>
【问题讨论】:
-
更改按钮内文本的颜色与更改
SVG元素的颜色是不同的。就个人而言,我可能会以不同的方式重写它,以便您可以传递某种Boolean来说明某事是否为active。现在,解决方法是将fill: #1471da;添加到您的&.activeTab选择器中。fill将针对SVG和color将针对按钮内的文本。 -
这能回答你的问题吗? How to change the color of an svg element?
-
是的!谢谢!
标签: javascript css reactjs typescript