获取图标属性并将其传递给 styled() 函数
Gets icon prop and passing it into styled() function
我正在获取图标属性并将其传递给样式化函数以基于它创建样式化图标
const IconComponent = ({ isActive, icon }) => {
const StyledIcons = styled(icon)`
fill: #1f6ed4;
& path {
fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
}
`
return <StyledIcons isActive={isActive} />
}
有效,但我收到如下警告:
是否有任何其他方法来创建我的 StyledIcons
组件
并同时获得图标道具 ?
您必须将 StyledIcons
移到 IconComponent
组件之外,并使用 as
prop 传递 icon
组件:
const StyledIcons = styled.svg`
fill: #1f6ed4;
& path {
fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
}
`
const IconComponent = ({ isActive, icon }) => {
return <StyledIcons as={icon} isActive={isActive} />
};
工作示例
并且如果您无法控制 icon
道具并希望避免第二次警告
Warning: React does not recognize the isActive
prop on a DOM element...
您可以在 isActive
属性前加上美元符号 ($),将其变成 transient prop:
const StyledIcons = styled.svg`
fill: #1f6ed4;
& path {
fill: ${(props) => (props.$isActive ? "#1F6ED4" : "#232323")};
}
`;
const IconComponent = ({ isActive, icon }) => {
return <StyledIcons as={icon} $isActive={isActive} />;
};
我正在获取图标属性并将其传递给样式化函数以基于它创建样式化图标
const IconComponent = ({ isActive, icon }) => {
const StyledIcons = styled(icon)`
fill: #1f6ed4;
& path {
fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
}
`
return <StyledIcons isActive={isActive} />
}
有效,但我收到如下警告:
是否有任何其他方法来创建我的 StyledIcons
组件
并同时获得图标道具 ?
您必须将 StyledIcons
移到 IconComponent
组件之外,并使用 as
prop 传递 icon
组件:
const StyledIcons = styled.svg`
fill: #1f6ed4;
& path {
fill: ${(props) => (props.isActive ? '#1F6ED4' : '#232323')};
}
`
const IconComponent = ({ isActive, icon }) => {
return <StyledIcons as={icon} isActive={isActive} />
};
工作示例
并且如果您无法控制 icon
道具并希望避免第二次警告
Warning: React does not recognize the
isActive
prop on a DOM element...
您可以在 isActive
属性前加上美元符号 ($),将其变成 transient prop:
const StyledIcons = styled.svg`
fill: #1f6ed4;
& path {
fill: ${(props) => (props.$isActive ? "#1F6ED4" : "#232323")};
}
`;
const IconComponent = ({ isActive, icon }) => {
return <StyledIcons as={icon} $isActive={isActive} />;
};