我有一个问题要问有经验的人,他们使用 React 制作了可共享的组件。为每个现有的 html 标签创建自定义反应组件是否合理?我的意思是,例如,如果我可以使用 html div
,那么创建自己的自定义是否有一些好处,<Div>
比如说,它将获得一些特定的参数作为道具(样式等)
问问题
854 次
2 回答
1
可能迟到了,但我目前正在设计一个像你描述的系统。我认为更高阶的组件将是实现这一目标的方法。这是我实施的系统的开始
function style (attr) {
const background = {
primary: 'blue',
...
}
const color = {...}
const size = {
padding: {...},
...
}
return {
background: background[attr.background] || undefined,
color: color[attr.color] || undefined,
size: {
padding: size.padding[attr.size] || undefined,
borderRadius: size.borderRadius[attr.size] || undefined
}
}
}
export const Tag = tag => React.memo(props => {
const Tag = tag
const theme = style(props)
return (
<Tag
className={classNames(
tag,
props.className,
theme.background !== undefined ? `bg-${theme.background}`: '',
theme.color !== undefined ? `text-${theme.color}`: '',
theme.size.padding !== undefined ? `pad-${theme.size.padding}`: '',
theme.size.borderRadius !== undefined ? `br-${theme.size.borderRadius}`: ''
)}
>
{props.children}
</Tag>
)
})
export const Section = Tag('section');
Section.displayName = "Section";
export const Article = Tag('article');
Article.displayName = "Article";
export const Header = Tag('header');
Header.displayName = "Header";
export const Footer = Tag('footer');
Footer.displayName = "Footer";
export const Span = Tag('span');
Span.displayName = "Span";
export const Strong = Tag('strong');
Strong.displayName = "Strong";
export const Div = Tag('div');
Div.displayName = "Div";
export const Em = Tag('em');
Em.displayName = "Em";
export const Ul = Tag('ul');
Ul.displayName = "Ul";
export const Li = Tag('li');
Li.displayName = "Li";
export const H1 = Tag('h1');
H1.displayName = "H1";
export const H2 = Tag('h2');
H2.displayName = "H2";
export const H3 = Tag('h3');
H3.displayName = "H3";
export const H4 = Tag('h4');
H4.displayName = "H4";
export const H5 = Tag('h5');
H5.displayName = "H5";
export const H6 = Tag('h6');
H6.displayName = "H6";
export const P = Tag('p');
P.displayName = "P";
于 2018-12-13T15:18:12.483 回答
0
可能它没有太大意义,div
因为它只是一个通用容器。但是对于像和链接这样的排版标签h1, h2...
,这可能是一个好主意。如果设计是一致的,这可以帮助您使代码更清晰。但当然,一切都取决于项目。
于 2018-06-07T15:40:33.963 回答