为什么我可以引用样式化组件上的组件,而其他组件则不能?



在样式化组件中,您可以使用此语法${Label}引用另一个 React 组件,但有时适用于某些组件,而其他组件则不然。

我已经在尝试阅读文档 https://www.styled-components.com/docs/advanced#referring-to-other-components,当我开始构建组件时,我无法使用 Label 组件来做到这一点,只能使用div 组件。

我将样式组件更新到最新的稳定版本。

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;

正如你从这行中看到

&:focus ~ label,
&:valid ~ label 

我正在使用标签库,并且我想使用我自定义的Label组件。

我需要这样工作:

&:focus ~ ${Label},
&:valid ~ ${Label} 

奇怪的是,在这一行中:

&:focus ~ ${Bar}:before 

条形图按预期工作。

这是因为当您在Input组件中使用${Label}时,它还不存在。将其向上移动到文件中,它应该按预期工作。

示例:https://codesandbox.io/embed/zen-cloud-f8mht

最新更新