javascript - 为什么我可以在 styled-components 上引用组件而其他人不能?
问题描述
在 styled-components 中,您可以使用此语法引用另一个 React 组件,${Label}
但有时可以与某些组件一起使用,而其他组件则不能。
我正在尝试阅读文档https://www.styled-components.com/docs/advanced#referring-to-other-components,当我开始构建组件时,我无法使用 Label 组件来完成,仅适用于 div 组件。
我将 styled-component 更新为最新的稳定版本。
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
酒吧按预期工作。
解决方案
这是因为当你${Label}
在Input
组件中使用它时它还不存在。将其向上移动到文件中,它应该可以按预期工作。
推荐阅读
- javascript - 如何在Javascript中获取具有where条件的对象名称数据列表?
- java - 查找最小窗口子字符串 - leetcode - 解决方案不起作用
- javascript - 在目标 url 中添加原始 url 作为 ?ref
- gams-math - 在不同版本的 GAMS 中得到不同的答案是否正常?
- python - 如何获得时间戳?
- php - 使用 Symfony Mailer 在 Twig 的模板化电子邮件中嵌入 Webpack 资产
- html - 如何为衬线字体设置css系统字体
- c# - Xamarin.Forms 字体 awesone 使用 Label
- apache - 引导层初始化期间发生错误 - NetBeans 中的 javafx.controller
- eclipse - 如何使用 ant 目标生成 .classpath 文件?