[英]Why I can refer a component on styled-components and others don't?
In styled-components you can refer another React component by using this syntax ${Label}
but works sometimes with some components and others don't. 在样式化组件中,您可以使用此语法
${Label}
引用另一个React组件,但有时可以与某些组件一起使用,而有些则不能。
I am trying already reading the documentation https://www.styled-components.com/docs/advanced#referring-to-other-components and when I start building a component I wasn't possible to do it with a Label component, only works with a div component. 我正在尝试阅读文档https://www.styled-components.com/docs/advanced#referring-to-other-components ,当我开始构建组件时,我无法使用Label组件来做,仅适用于div组件。
I update the styled-component to the latest stable version. 我将样式化组件更新为最新的稳定版本。
import React from "react";
import styled, { css } from "styled-components";
// https://codepen.io/lewisvrobinson/pen/EyZwjR
// VARIABLES // ============================== //
const bgColor = "#424242";
const hlColor = "#2196F3";
const mutedColor = "Black";
const transTime = "300ms";
const width = "320px";
// FORM // ============================== //
const Box = styled.div`
position: relative;
margin: 45px 0;
`;
const Input = styled.input.attrs({
type: "text",
required: "required"
})`
background: none;
color: ${mutedColor};
font-size: 18px;
padding: 10px 10px 10px 5px;
display: block;
width: ${width};
border: none;
border-radius: 0;
border-bottom: 1px solid ${mutedColor};
&:focus {
outline: none;
}
&:focus ~ label,
&:valid ~ label {
top: -14px;
font-size: 12px;
color: ${hlColor};
}
&:focus ~ ${Bar}:before {
width: ${width};
}
`;
const Label = styled.label`
color: ${mutedColor};
font-size: 16px;
font-weight: normal;
position: absolute;
pointer-events: none;
left: 5px;
top: 10px;
transition: ${transTime} ease all;
`;
const Bar = styled.span`
position: relative;
display: block;
width: ${width};
&:before {
content: "";
height: 2px;
width: 0;
bottom: 0px;
position: absolute;
background: ${hlColor};
transition: ${transTime} ease all;
left: 0%;
}
`;
const TextField = props => {
return (
<Box>
<Input />
<Bar></Bar>
<Label>Name</Label>
</Box>
);
};
export default TextField;
As you can see in this lines 如您所见
&:focus ~ label,
&:valid ~ label
I am using the label base, and I want to use the Label
component that I custom. 我正在使用标签库,并且想要使用自定义的
Label
组件。
I need that works like this: 我需要这样的作品:
&:focus ~ ${Label},
&:valid ~ ${Label}
The weird part is that in this line: 奇怪的是,在这一行:
&:focus ~ ${Bar}:before
Bar works as expected. 酒吧按预期工作。
It is because when you are using ${Label}
in the Input
component it does not exist yet. 这是因为当您在
Input
组件中使用${Label}
,该组件尚不存在。 Move it up the file and it should work as expected. 将其移动到文件上,它将按预期工作。
Example: https://codesandbox.io/embed/zen-cloud-f8mht 示例: https : //codesandbox.io/embed/zen-cloud-f8mht
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.