【问题标题】:React & Typescript, styled components & childrenReact 和 Typescript,样式化的组件和子组件
【发布时间】:2020-06-03 07:33:42
【问题描述】:

我已经尝试了很多不同的组合来让它工作,但它没有应用我为StyledLines 组件编写的样式,它们自己工作得很好!将StyledLines 组件用作子组件,它不起作用。 Target 组件样式按预期工作。

import React, { Fragment, FunctionComponent } from 'react';
import styled from '@emotion/styled';


interface Crosshair {
  size: number;
  thickness: number;
}


const Target = styled.div<Crosshair>`
  position:absolute;
  &:before {
    content: '';
    display:block;
    position:absolute;
    top:50%;
    left:50%;
    background-color:transparent;
    border-color:#2fd5d5;
    margin-left:-${({size}) => size / 4}px;
    margin-top:-${({thickness}) => thickness / 4}px;
    width:${({size}) => size / 2}px;
    height:${({thickness}) => thickness / 2}px;
  }
`;

const Lines: FunctionComponent = ({children}) => <div className="line">{children}</div>;

const StyledLines = styled(Lines)<Crosshair>`
  position:absolute;
  &:nth-of-type(1) {
    top:0;
    left:0;
  }
  &:nth-of-type(2) {
    top:0;
    right:0;
  }
  &:nth-of-type(3) {
    bottom:0;
    right:0;
  }
  &:nth-of-type(4) {
    bottom:0;
    left:0;
  }
  &:after, &:before {
    content: '';
    display:block;
    position:absolute;
    top:50%;
    left:50%;
    background:#2fd5d5;
    margin-left:-${({size = 2}) => size / 2}px;
    margin-top:-${({thickness = 24}) => thickness / 2}px;
    width:${({size = 2}) => size}px;
    height:${({thickness = 24}) => thickness}px;
  }
  &:before {
    transform: rotateZ(90deg);
  }
`;


export default function Crosshairs() {
  return <Fragment>
    <div>
      {[0,1,2,3].map(i => <StyledLines key={i} size={24} thickness={2}>
        <Target size={24} thickness={2} />
      </StyledLines>)}
    </div>
  </Fragment>;
}

【问题讨论】:

    标签: reactjs typescript styled-components emotion


    【解决方案1】:

    Lines 是一个普通的 React 组件,而不是一个样式化的组件,所以你必须将 className 属性传递给你想要样式化的 DOM 部分:

    const Lines: FunctionComponent = ({children, className}) => <div className={`line ${className}`}>{children}</div>;
    

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 2021-04-13
      • 2019-12-30
      • 2020-03-08
      • 2021-01-13
      • 2019-10-27
      • 2022-07-19
      • 2021-07-03
      • 2021-02-04
      相关资源
      最近更新 更多