[英]Structuring and reusing React Styled-components and native components
I'm a backend engineer who is learning frontend – very much a noob at this point.我是一名正在学习前端的后端工程师——在这一点上非常菜鸟。 I'm currently learning React and came across styled-components¬, which seems like a great way of handling styling whilst using components.我目前正在学习 React 并遇到了 styled-components¬,这似乎是在使用组件的同时处理样式的好方法。 I'm currently having issues using styled-components with native [React] components and changing them in a modular fashion.我目前在将样式化组件与本机 [React] 组件一起使用并以模块化方式更改它们时遇到问题。 I can't think of a viable option of doing what I want to do, or more likely, I'm doing it wrong.我想不出一个可行的选择来做我想做的事,或者更可能的是,我做错了。 Use case: Here my folder setup:用例:这里是我的文件夹设置:
enter image description here在此处输入图像描述
I've decided to include two files for each component:我决定为每个组件包含两个文件:
Here the styles.js:这里是 styles.js:
const StyledDeleteButton = styled.button`
width: auto;
height: 30px;
font-size: 20px;
text-align: center;
color: green;
border: none;
border-radius: 5px;
&:hover {
color: red;
}
`;
Here the components.js:这里是 components.js:
const DeleteButton = () => <StyledDeleteButton>Delete</StyledDeleteButton>;
What I want to achieve: In my styles, I don't want to apply any positioning now - but can later via props of course.我想要实现的目标:在我的风格中,我现在不想应用任何定位 - 但当然可以稍后通过道具。 But I want to use the native component which has the Delete text.但我想使用具有删除文本的本机组件。 So, my question is, how can I apply addition styling on the component?所以,我的问题是,如何在组件上应用附加样式?
Inheriting the native component, but doesn't seem possible.继承本机组件,但似乎不可能。 I can apply what I want via CSS but want to be consistent as I can.我可以通过 CSS 应用我想要的东西,但我希望尽可能保持一致。
If you don't want to apply any styles for now and do it later, you can pass className
as a prop like this, and just use the native <button />
element如果你暂时不想应用任何样式,以后再做,你可以像这样将className
作为 prop 传递,并且只使用原生的<button />
元素
const DeleteButton = ({className}) => <button className={className}>Delete</button>;
Then later for adding styles, you have to use the styled
function on the DeleteButton
component然后稍后要添加样式,您必须在DeleteButton
组件上使用styled
函数
const StyledDeleteButton = styled(DeleteButton)`
width: auto;
height: 30px;
font-size: 20px;
text-align: center;
color: green;
border: none;
border-radius: 5px;
&:hover {
color: red;
}
`;
Styling any component from the doc为文档中的任何组件设置样式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.