[英]Why I can refer a component on styled-components and others don't?
在樣式化組件中,您可以使用此語法${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}
,該組件尚不存在。 將其移動到文件上,它將按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.