javascript - 为什么我可以在 styled-components 上引用一个组件而其他人不能?

标签 javascript html css reactjs styled-components

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

我正在尝试阅读文档 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 base,我想使用我自定义的Label组件。

我需要这样工作:

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

奇怪的是这一行:

  &:focus ~ ${Bar}:before 

栏按预期工作。

最佳答案

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

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

关于javascript - 为什么我可以在 styled-components 上引用一个组件而其他人不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841049/

相关文章:

html - 使 wrapper 适合 100% 的宽度和高度

javascript - 在javascript中输入字符串

javascript - POST 请求时 Mongoose 验证错误

html - 问题居中动画

html - 标签未显示在 D3 圆环图上

php - 隐藏移动内容

javascript - 如果在 CSS 上声明显示,为什么 element.style.display 为空

javascript - 如何动态添加选择框,从数据库中检索数据

javascript - jQuery .submit 方法

html - 以类 X 定位除第一个元素以外的所有元素,其中父元素在开头有另一个没有类 X 的元素