【问题标题】:Styled-components extends propsStyled-components 扩展了 props
【发布时间】:2021-09-22 14:34:42
【问题描述】:

我有一个这样的就绪按钮,这些是我希望每个按钮都具备的功能。

如果我为图标发送道具,我不希望创建图标,如果我不发送,我不希望创建它。

    import Icon from 'components/icons/Icon';
import styled from 'styled-components';

const Button = styled.button`
  border-radius: 8px;
  color: white;
  cursor: pointer;
  outline: none;
  border: none;
  display: flex;
  font-family: 'DM Sans', sans-serif;
  font-weight: 700;
`;

const DefaultButton = ({ name, children }) => {
  return (
    <Button>
      {name && <Icon name={name}></Icon>}
      {children}
    </Button>
  );
};

export default DefaultButton;

我有一个这样自定义的按钮组件。 我希望它从默认按钮继承其属性。 但是Primary 的功能并没有出现在我的按钮上。 我想知道我应该解决什么,谢谢朋友

import styled from 'styled-components';
import { sizes } from 'constants/components/button';
import { colors } from 'theme';
import DefaultButton from './DefaultButton';

const PrimaryButton = styled(DefaultButton)`
  padding: ${({ size }) => sizes[size]} 48px;
  background-color: ${colors.primary.color};
  font-size: 14px;
  font-style: bold;

  &:focus {
    border: 1px solid #ffffff;
    box-sizing: border-box;
    box-shadow: 0px 0px 0px 3px rgba(24, 207, 152, 1);
  }
  &:hover {
    background-color: ${colors.primary.pressed};
    box-shadow: 0px 14px 24px rgba(23, 207, 151, 0.3);
    color: white;
  }

  &:disabled {
    background-color: ${colors.primary.disabled};
    cursor: not-allowed;
    pointer-events: none;
    color: white;
  }
`;

export default PrimaryButton;

这就是我使用组件的方式,我希望它是这样的

<PrimaryButton size="md" name="test">
        Sign in
      </PrimaryButton>

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    我发现@svrbst 解决方案非常有效。我扩展它以添加其他依赖项,如图所示,它工作正常。这是分叉的codesandbox

    【讨论】:

      【解决方案2】:

      如果你想扩展/覆盖另一个组件的样式,你需要传递className 属性,如docs 中所述。

      styled 方法在您自己或任何第三方组件上都能完美运行,只要它们将传递的 className 属性附加到 DOM 元素。

      const DefaultButton = ({ name, children, className }) => {
        return (
          <Button className={className}>
            {name && <Icon name={name}></Icon>}
            {children}
          </Button>
        );
      };
      

      【讨论】:

      • 但是我不发送类名怎么办
      • className 是传递给组件的隐式道具。只需从道具中解构它并将其传递下去。我在这个codesandbox 中实现了一个简单的例子
      猜你喜欢
      • 2021-09-19
      • 2020-06-07
      • 2020-05-28
      • 2019-02-18
      • 2018-10-29
      • 2021-06-09
      • 2018-04-15
      • 2019-03-14
      • 1970-01-01
      相关资源
      最近更新 更多