我如何创建一个 Typography 组件,它可以与所有标题标签、h1、h2、h3 等重用。
在理想世界中,我想到了下面的代码,但我仍然没有在文档中找到如何正确编写它。
export const Typography = (level) => styled(level)`
..style here
`;
h1:
<Typography level={h1}>Text here</Typography>
有什么方法可以重现吗?
最佳答案
这是一个完整的解决方案,我认为它非常符合您的问题。
使用动态标签名称(与其他答案一样)并包含一个代表您的 Typography
组件的样式组件。我将其命名为 StyledHeader
,因为它实际上只与标题有关。
更广泛的用途是允许通过相同的代码发送任何标签,以将排版应用到任何元素。我让您对此进行扩展。
一个工作示例:Demo
import React from "react";
import "./style.css";
import styled from 'styled-components'
const Header = ({tagName, ...otherProps}) => {
const Tag = tagName;
const defaultProps = {
tagName: 'div'
};
return <Tag {...otherProps}/>
}
const StyledHeader = styled(Header)`
font-style: italic;
`;
export default function App() {
const headers = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
const output = headers.map(header =>
<StyledHeader tagName={header}>Content</StyledHeader>
);
return (
<div>
{output}
</div>
);
}
关于javascript - 如何创建可用作 h1、h2、h3、h4 等的 Typography 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66375680/