- 本文爲 Marno 翻譯,轉載必須保留出處!
- 公衆號【 aMarno 】,關注後回覆 RN 加入交流羣
- React Native 優秀開源項目大全:www.marno.cn
React Native 的 Style 屬性採用的是駝峯命名法,對於從原生轉 RN 的開發者來講可能不會感到陌生,可是對於習慣了中線或者下劃線命名的 Web 開發者來講,感受可能就不是那麼順手了。css
今天推薦一個組件:styled-components,可讓 Web 開發者繼續使用熟悉的 CSS 命名方式在 RN 中進行樣式的編寫。固然這只是這個組件的一個特性,熟悉 ReactJS 的 Web 開發者可能知道,這個工具可讓咱們更快速的進行組件封裝,用事後就真的回不去了!並且最近更新到了 V2 版本,功能更強大,體積直接小了近一半。react
網上搜了下相關的文章,基本都是講在 React Web 中的使用,因此我今天就介紹下在 React Native 中的使用,來看下這個組件到底是如何幫咱們提升開發效率的。git
不想看我囉嗦的也能夠直接去看官方文檔,地址以下↓↓↓github
1.安裝npm
npm install --save styled-components複製代碼
2.簡單使用框架
import styled from 'styled-components/native';
const StyledView = styled.View`
flex:1;
align-items:center;
justify-content:center;
background-color: papayawhip;
`;
const StyledText = styled.Text`
color: palevioletred;
`;
class MarnoTestStyledComponents extends Component {
render() {
return (
< StyledView>
< StyledText> Hello Marno! < /StyledText>
< /StyledView>
)
}
}複製代碼
這麼看起來好像並無比直接寫 StyleSheet 高效了多少,那讓咱們接着往下看。我以爲這個組件的好用之處,可能只有多用纔能有所體會, 最爲直觀的就是會少了一些代碼(好比在設置 padding 或 margin 的時候)。ide
1.拓展工具
const StyledTextExtend = StyledText.extend`
color: tomato;
`;複製代碼
2.參數傳遞佈局
const StyledTextAdapt = styled.Text`
color: ${props => props.primary ? 'green' : 'blue'};
`;
class MarnoTestStyledComponents extends Component {
render() {
return (
< StyledView>
< StyledTextAdapt>3.Hello Marno!< /StyledTextAdapt>
< StyledTextAdapt primary>4.Hello Marno!< /StyledTextAdapt>
< /StyledView>
)
}
}複製代碼
3.缺省值學習
const StyledTextAttach = styled.Text.attrs({
color:props=>props.color || '#00ff00',
})`
height:30px;
color: ${props => props.color};
`;
class MarnoTestStyledComponents extends Component {
render() {
return (
< StyledView>
< StyledTextAttach>6.Hello Marno< /StyledTextAttach>
< StyledTextAttach color='#333333'>7.Hello Marno< /StyledTextAttach>
< /StyledView>
)
}
}複製代碼
1.主題
const StyledTextTheme = styled.Text`
color:${props => props.theme.color};
background:${props => props.theme.background};
border:${props => props.theme.border};
border-radius:${props => props.theme.borderRadius};
padding:10px 10px 10px 10px;
margin:5px 10px;
`;
StyledTextTheme.defaultProps = {
theme: {
color:'#00ffff',
background: 'white',
border:'1px',
borderRadius:'4px',
}
}
const theme2 = {
color:'white',
background: 'black',
border:'3px',
borderRadius:'10px',
};
class MarnoTestStyledComponents extends Component {
render() {
return (
< StyledView>
< ThemeProvider theme={theme2}>
< StyledTextTheme>9.Hello Marno< /StyledTextTheme>
< /ThemeProvider>
< /StyledView>
)
}
}複製代碼
github 上已經有不少 styled-components 衍生出來的框架,我在這裏羅列幾個,並不必定都和 RN 相關,可是能夠幫咱們開下腦洞,瞭解下國外的大神是怎麼使用這個工具來提升生產效率的。
styled-components 的確是解決了咱們的一些痛點,可是使用了該組件後就不能暢快的使用 Webstrom 中的代碼提示功能了,這對於接觸 RN 不久的人來講,可能實用性會下降一些。並且相比 React Web 來講,目前對 React Native 的支持還稍微差了一些,不過做者確定會不斷完善的。
最後聲明一下,這並非 styled-components 中文使用指南 ,因此並無把所有功能羅列出來,若是看完文章對這個組件產生興趣的,能夠直接跳轉到官方文檔去學習,也歡迎掃碼關注公衆號後,加入 RN 交流羣進行討論。
demo地址:github.com/MarnoDev/rn…
(demo中僅寫了 Android 版本)