我经常使用样式组件,这些组件总是具有相同的内容,例如“•”或“ |”。
我不知道这样的事情是否可能:
const Divider = styled.div.attrs({
text: '|',
})({
margin: '0 5px',
})
<Divider />
而不是像这样编写和调用它:
const Divider = styled.div({
margin: '0 5px',
})
<Divider>|</Divider>
PS。我知道text
不是有效的HTML属性
答案 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>
);