[英]Styled component: Herencia
I am writing a React application with styled components, creating a library of reusable components for my application, but I encounter the problem of inheritance between sister components when trying to give a property to a label that is next to my input when the input is required, but it does not work.我正在编写一个带有样式组件的 React 应用程序,为我的应用程序创建一个可重用组件库,但是当我尝试为需要输入时我的输入旁边的 label 提供属性时,我遇到了姐妹组件之间的 inheritance 问题,但它不起作用。 I have tried with:
我尝试过:
// Form.js
import { StyledLabel, StyledInput } from './styles.js'
<StyledLabel>Mi Label 1</StyledLabel>
<StyledInput required/>
// ./styles.js
import styled from 'styled-components'
export const StyledInput = styled.input`
border: 1px #dddd solid;
`
export const StyledLabel = styled.label`
font-size: 10px;
${StyledInput}['required'] + & {
&::after {
content: '*'
}
}
`
The result only returns the form without the *结果只返回不带 * 的表单
Does anyone know how I can detect from Styled Components when an input has the required HTML attribute, and show the *有谁知道当输入具有所需的 HTML 属性时我如何从样式化组件中检测到,并显示 *
Pseudo-selectors in styled-components work just like they do in CSS.样式组件中的伪选择器的工作方式与 CSS 中的一样。 (or rather, Sass).
(或者更确切地说,萨斯)。
So you can do what you want this way:所以你可以用这种方式做你想做的事:
const Wrapper = styled.div`
label {
&:after {
content: "${p => p.required && "*"}";
color: red;
}
}`;
const Form = () => {
return (
<Wrapper required>
<label>Mi Label 1</label>
<input />
</Wrapper>
);
};
But if you want don't want to pass props of the input element to its parent you can do it this way:但是如果你不想将输入元素的道具传递给它的父元素,你可以这样做:
const Wrapper = styled.div`
display: flex;
flex-direction: row-reverse;
align-items: center;
`;
const Example = styled.input`
+ label {
&:after {
content: "${p => p.required && "*"}";
color: red;
}
}
`;
const Form = () => {
return (
<Wrapper required>
<Example />
<label>My Label 1</label>
</Wrapper>
);
};
more info in resources:资源中的更多信息:
Before and After pseudo classes used with styled-components 与样式组件一起使用的之前和之后伪类
https://github.com/styled-components/styled-components/issues/388 https://github.com/styled-components/styled-components/issues/388
https://github.com/styled-components/styled-components/issues/74 https://github.com/styled-components/styled-components/issues/74
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.