可能我們希望某個經常使用的組件,在特定場景下可以稍微更改其樣式.當然我們可以通過 props 傳遞插值的方式來實現,但是對于某個只需要重載一次的樣式來說這樣做的成本還是有點高.
創(chuàng)建一個繼承其它組件樣式的新組件,最簡單的方式就是用構造函數styled()包裹被繼承的組件.下面的示例就是通過繼承上一節(jié)創(chuàng)建的按鈕從而實現一些顏色相關樣式的擴展:
// 上一節(jié)創(chuàng)建的沒有插值的 Button 組件 const Button = styled.button` color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; // 一個繼承 Button 的新組件, 重載了一部分樣式 const TomatoButton = styled(Button)` color: tomato; border-color: tomato; `; render( <div> <Button>Normal Button</Button> <TomatoButton>Tomato Button</TomatoButton> </div> );
可以看到,新的TomatoButton仍然和Button類似,我們只是添加了兩條規(guī)則.
In some cases you might want to change which tag or component a styled component renders.這在構建導航欄時很常見,例如導航欄中同時存在鏈接和按鈕,但是它們的樣式應該相同.
在這種情況下,我們也有替代辦法(escape hatch). 我們可以使用多態(tài) "as" polymorphic prop 動態(tài)的在不改變樣式的情況下改變元素:
const Button = styled.button` display: inline-block; color: palevioletred; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; const TomatoButton = styled(Button)` color: tomato; border-color: tomato; `; render( <div> <Button>Normal Button</Button> <Button as="a" href="/">Link with Button styles</Button> <TomatoButton as="a" href="/">Link with Tomato Button styles</TomatoButton> </div> );
這也完美適用于自定義組件:
const Button = styled.button`
display: inline-block;
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
const ReversedButton = props => <button {...props} children={props.children.split('').reverse()} />
render(
<div>
<Button>Normal Button</Button>
<Button as={ReversedButton}>Custom Button with Normal Button styles</Button>
</div>
);
styled方法適用于任何最終向 DOM 元素傳遞 className 屬性的組件,當然也包括第三方組件.
注意在 react-native 中,請使用 style 而不是 className.
// 下面是給 react-router-dom Link 組件添加樣式的示例 const Link = ({ className, children }) => ( <a className={className}> {children} </a> ); const StyledLink = styled(Link)` color: palevioletred; font-weight: bold; `; render( <div> <Link>Unstyled, boring Link</Link> <br /> <StyledLink>Styled, exciting Link</StyledLink> </div> );
注意也可以傳遞標簽給styled(), 比如: styled("div"). 實際上styled.tagname的方式就是 styled(tagname)`的別名.
更多建議: