有許多方法可以實現(xiàn)覆蓋組件樣式.話雖如此,很難在不使用廣為人知的CSS選擇器范式的情況下讓使用插值變得輕松.
styled-components 通過"component selector"干凈利落的解決了這個問題. 當一個組件由styled()工廠方法創(chuàng)建或是被其包裝后,同時也會被分配一個 stable CSS 類用于定位.這實現(xiàn)了非常強力的組合模式而無需在命名和避免選擇器沖突上手忙腳亂.
如下例子實現(xiàn)了 Icon 組件對它父組件 Link hover 的響應:
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, 但是這樣就必須要同時考慮這兩套規(guī)則來理解 Icon 組件的行為.
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} { } `
更多建議: