我們可以將 props 以插值的方式傳遞給styled component,以調(diào)整組件樣式.
下面這個 Button 組件持有一個可以改變color的primary屬性. 將其設(shè)置為 ture 時,組件的background-color和color會交換.
const Button = styled.button` /* Adapt the colors based on primary prop */ background: ${props => props.primary ? "palevioletred" : "white"}; color: ${props => props.primary ? "white" : "palevioletred"}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid palevioletred; border-radius: 3px; `; render( <div> <Button>Normal</Button> <Button primary>Primary</Button> </div> );
如果添加樣式的目標(biāo)是 DOM 元素 (如styled.div), styled-components 會傳遞已知的 HTML 屬性給 DOM. 如果是一個自定義的 React 組件 (如styled(MyComponent)), styled-components 會傳遞全部 props.
以下示例展示如何傳遞 Input 組件的 props 到已裝載的 DOM 節(jié)點, as with React elements.
// 創(chuàng)建一個給<input>標(biāo)簽添加若干樣式的 Input 組件 const Input = styled.input` padding: 0.5em; margin: 0.5em; color: ${props => props.inputColor || "palevioletred"}; background: papayawhip; border: none; border-radius: 3px; `; // 渲染兩個樣式化的 text input,一個標(biāo)準(zhǔn)顏色,一個自定義顏色 render( <div> <Input defaultValue="@probablyup" type="text" /> <Input defaultValue="@geelen" type="text" inputColor="rebeccapurple" /> </div> );
注意, inputColor prop并沒有傳遞給 DOM, 但是type和defaultValue 都傳遞了. styled-components足夠智能,會自動過濾掉所有非標(biāo)準(zhǔn) attribute.
更多建議: