繁体   English   中英

样式组件:Herencia

[英]Styled component: Herencia

我正在编写一个带有样式组件的 React 应用程序,为我的应用程序创建一个可重用组件库,但是当我尝试为需要输入时我的输入旁边的 label 提供属性时,我遇到了姐妹组件之间的 inheritance 问题,但它不起作用。 我尝试过:

// Form.js
import { StyledLabel, StyledInput } from './styles.js'
<StyledLabel>Mi Label 1</StyledLabel>
<StyledInput required/>

// ./styles.js
import styled from 'styled-components'

export const StyledInput = styled.input`
  border: 1px #dddd solid;
`

export const StyledLabel = styled.label`
  font-size: 10px;
  ${StyledInput}['required'] + & {
    &::after {
      content: '*'
    }
  }
`

结果只返回不带 * 的表单

有谁知道当输入具有所需的 HTML 属性时我如何从样式化组件中检测到,并显示 *

样式组件中的伪选择器的工作方式与 CSS 中的一样。 (或者更确切地说,萨斯)。
所以你可以用这种方式做你想做的事:

const Wrapper = styled.div`
label {
    &:after {
    content: "${p => p.required && "*"}";
    color: red;
  }
}`;
const Form = () => {
return (
    <Wrapper required>
    <label>Mi Label 1</label>
    <input />
    </Wrapper>
);
};

但是如果你不想将输入元素的道具传递给它的父元素,你可以这样做:

const Wrapper = styled.div`
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
`;
const Example = styled.input`
+ label {
      &:after {
        content: "${p => p.required && "*"}";
        color: red;
      }
    }
`;
const Form = () => {
  return (
    <Wrapper required>
      <Example />
      <label>My Label 1</label>
    </Wrapper>
  );
};

资源中的更多信息:
与样式组件一起使用的之前和之后伪类

https://github.com/styled-components/styled-components/issues/388

https://github.com/styled-components/styled-components/issues/74

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM