【问题标题】:Misunderstanding of Styled-components concept对 Styled-components 概念的误解
【发布时间】:2017-12-27 15:18:59
【问题描述】:

我正在尝试制作一个带有文本和图标的基本按钮。 这是我现在的代码:

IconNotification.js:

import React from "react";
import styled from "styled-components";

const Icon = styled.svg`
  height: ${props => props.height || '24px'};
  width: ${props => props.height || '24px'};
  fill: red
`;

const IconNotification = (props) => {
  console.log(props)
  return (
    <Icon viewBox="0 0 24 24" fill={props.fill}>
      <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z" />
    </Icon>
  )
}


export default IconNotification;

ButtonAddAlert.js:

import React from 'react'
import styled from 'styled-components'

import Button from 'components/Button'
import IconNotification from 'components/Icon/IconNotification'

const IconNotificationWithHover = styled(IconNotification)`
  ${Button}:hover & {
    fill: blue
  }
`

const ButtonAddAlert = ({ iconColor }) => (
  <Button>
    Add an alert
    <IconNotificationWithHover />
  </Button>
)

export default ButtonAddAlert

我想要:

  • 当我悬停按钮时,svg 图标会改变颜色,但仅适用于这种特定情况
  • 还可以通过传递一个 prop 来更改 svg 图标的颜色(如果我需要在另一个组件中使用相同的图标)

我觉得我没有正确理解 styled-components 的概念,因为我现在不明白它是如何实现的。

如果你知道我做错了什么,请告诉我! 谢谢,

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    有几点:

    • fill 可以被样式化组件处理。

    • IconNotification 应该在 Button 内部引用,而不是相反,因为它的样式依赖于 Button 状态。这是 JS 中 CSS 的常见模式。

    图标.js

    const Icon = styled.svg`
      height: ${props => props.height || "24px"};
      width: ${props => props.height || "24px"};
      fill: ${props => props.fill || "red"};
    `;
    

    Button.js

    import Icon from "./Icon";
    
    const Button = styled.button`
      &:hover > ${Icon}${Icon} { // twice for specificity
        fill: blue;
      }
    `;
    

    这是代码沙箱的链接,您可以使用它:https://codesandbox.io/s/n370mljrqp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2021-04-06
      相关资源
      最近更新 更多