我有时提取本地的Tailwind样式的组件,如下所示:
const Container: React.FC = ({ children }) => (
<div className="bg-white px-5 py-5">
{children}
</div>
);为了使这更容易,我希望有一个帮助器styleElement函数来为我创建Container,有点像这样:
const Container = styleElement("div", "bg-white px-5 py-5");如何编写styleElement函数,以便将Container正确地键入为div,并将其className设置为默认值?Ie:
// Renders as <div className="bg-white px-5 py-5 text-red">…</div>
<Container className="text-red">…</Container>我强调,我希望保持输入正确/紧凑,这样调用styleElement("a", …)将生成一个组件,该组件接受a的正确道具。
PS。我见过this related question,但是我很难把类型从答案转到我想要的。
发布于 2022-09-07 10:54:24
功能
function createElement(tag, classes) {
return ({ children }) => {
const Element = tag;
return <Element className={classes}>{ children }</Element>
}
}用法
function App() {
const StyledDiv = createElement('div', 'p-4')
return (
<div className="App">
<StyledDiv>Hello</StyledDiv>
</div>
);
}基本道具
function createElement(tag: keyof JSX.IntrinsicElements, classes: string) {
return ({
children,
...props
}: React.DetailedHTMLProps<
React.BlockquoteHTMLAttributes<HTMLElement>,
HTMLElement
>) => {
return React.createElement(tag, { ...props, className: classes }, children);
};
}https://stackoverflow.com/questions/73633387
复制相似问题