如何创建一个排版组件,它可以与所有的标题标签、h1、h2、h3..etc一起重用。
在理想的情况下,我想到了下面的代码,但我仍然没有在文档中找到如何正确地编写它。
export const Typography = (level) => styled(level)`
..style here
`;h1:
<Typography level={h1}>Text here</Typography>有没有办法重现这一切?
发布于 2021-02-26 04:46:24
这里有一个完整的解决方案,我认为它非常符合您的问题。
使用动态标记名(就像其他答案一样),并包含一个代表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>
);
}发布于 2021-02-26 04:15:35
您可以尝试使用ejs。并像这样编写代码:
<% if(parameter == 'true'){ %>
<h1>some text</h1>
<% } %>
<% if(parameter2 == 'true'){ %>
<h2>text2</h2>
<% } %>
在js文件中,它将如下所示:
render('filename.ejs',{parameter: true, parameter2: false})
我认为它将适用于小项目,对于较大的项目,您将需要找到更好的解决方案。
发布于 2021-02-26 04:39:42
如果你想使用普通的标签,你可以像这样使用简单的结构:
const styleMap={
"h1":{
margin: '40px',
border: '5px solid pink'
},
...
}
export const Typography=({Tag, children, ...otherProps})=>{
return <Tag {...otherProps} style={styleMap[Tag]}>{children}</Tag>
}或带有类样式的变体:
import './styles.css'
const styleMap={
h1:'h1_styled',
...
}
export const Typography = ({ Tag, children, ...otherProps }) = {
return React.createElement(
Tag || 'div',
{...otherProps, style:styleMap[Tag]},
children
);
}对于更复杂的任务,只需考虑ready-made solutions或其source code
https://stackoverflow.com/questions/66375680
复制相似问题