styled-components 參考其他部件

2020-07-24 18:00 更新

Referring to other components

參考其他部件

有許多方法可以實(shí)現(xiàn)覆蓋組件樣式.話雖如此,很難在不使用廣為人知的CSS選擇器范式的情況下讓使用插值變得輕松.

styled-components 通過"component selector"干凈利落的解決了這個(gè)問題. 當(dāng)一個(gè)組件由styled()工廠方法創(chuàng)建或是被其包裝后,同時(shí)也會被分配一個(gè) stable CSS 類用于定位.這實(shí)現(xiàn)了非常強(qiáng)力的組合模式而無需在命名和避免選擇器沖突上手忙腳亂.

如下例子實(shí)現(xiàn)了 Icon 組件對它父組件 Link hover 的響應(yīng):

const Link = styled.a`
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background: papayawhip;
  color: palevioletred;
`;

const Icon = styled.svg`
  flex: none;
  transition: fill 0.25s;
  width: 48px;
  height: 48px;

  ${Link}:hover & {
    fill: rebeccapurple;
  }
`;

const Label = styled.span`
  display: flex;
  align-items: center;
  line-height: 1.2;

  &::before {
    content: '?';
    margin: 0 10px;
  }
`;

render(
  <Link href="#">
    <Icon viewBox="0 0 20 20">
      <path d="M10 15h8c1 0 2-1 2-2V3c0-1-1-2-2-2H2C1 1 0 2 0 3v10c0 1 1 2 2 2h4v4l4-4zM5 7h2v2H5V7zm4 0h2v2H9V7zm4 0h2v2h-2V7z"/>
    </Icon>
    <Label>Hovering my parent changes my style!</Label>
  </Link>
);

可以在 Link 組件內(nèi)嵌套樣式color-changing, 但是這樣就必須要同時(shí)考慮這兩套規(guī)則來理解 Icon 組件的行為.

Caveat 警告

This behaviour is only supported within the context of Styled Components: attempting to mount B in the following example will fail because component A is an instance of React.Component not a Styled Component.

class A extends React.Component {
  render() {
    return <div />
  }
}

const B = styled.div`
  ${A} {
  }
`

The error thrown - Cannot call a class as a function - occurs because the styled component is attempting to call the component as an interpolation function.

However, wrapping A in a styled() factory makes it eligible for interpolation -- just make sure the wrapped component passes along className.

class A extends React.Component {
  render() {
    return <div className={this.props.className} />
  }
}

const StyledA = styled(A)``

const B = styled.div`
  ${StyledA} {
  }
`


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號