用自包含的文本声明样式化组件

时间:2018-11-21 21:14:48

标签: reactjs styled-components

我经常使用样式组件,这些组件总是具有相同的内容,例如“•”或“ |”。

我不知道这样的事情是否可能:

const Divider = styled.div.attrs({
  text: '|',
})({
  margin: '0 5px',
})
<Divider />

而不是像这样编写和调用它:

const Divider = styled.div({
  margin: '0 5px',
})
<Divider>|</Divider>

PS。我知道text不是有效的HTML属性

1 个答案:

答案 0 :(得分:1)

一种方法是传递type并通过switch运行它。关于开发人员可以期望看到哪种Divider的声明,将会更具声明性。

工作示例https://codesandbox.io/s/5y1n9mv08x

components / Divider.js (可以在StyledDivider组件文件中内联完成,但为清楚起见,我将其分成了自己的文件)

import React from "react";
import PropTypes from "prop-types";

const typeReducer = type => {
  switch (type) {
    case "backslash":
      return "\\";
    case "dash":
      return "-";
    case "dot":
      return "•";
    case "pipe":
      return "|";
    case "forwardslash":
      return "/";
    default:
      return <hr />;
  }
};

const Divider = ({ className, type }) => (
  <div className={className}>
    {typeReducer(type)}
  </div>
);

export default Divider;

Divider.propTypes = {
  className: PropTypes.string.isRequired,
  type: PropTypes.string
};

component / StyledDivider.js

import styled from "styled-components";
import Divider from "./Divider";

export default styled(Divider)`
  display: inline;
  color: #03a9f3;
  font-weight: bold;
  font-size: 20px;
  margin: 0 5px;
`;

components / Header.js

import React from "react";
import Link from "./StyledLink";
import Divider from "./StyledDivider";

export default () => (
  <nav className="container">
    <Link primary link="/">
      Home
    </Link>
    <Divider type="dot" />
    <Link danger link="/about">
      About
    </Link>
    <Divider type="pipe" />
    <Link link="/portfolio">Portfolio</Link>
    <Divider type="pipe" />
    <Link danger link="/legal">
      Legal
    </Link>
    <Divider type="dot" />
    <Link primary link="/contact">
      Contact
    </Link>
    <Divider />
  </nav>
);