W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
React Native 不實現 CSS,而是依賴于 JavaScript 來為你的應用程序設置樣式。這是一個有爭議的決定,你可以閱讀那些幻燈片,了解背后的基本原理。
在 React Native 中聲明樣式的方法如下:
var styles = StyleSheet.create({ base: { width: 38, height: 38, }, background: { backgroundColor: '#222222', }, active: { borderWidth: 2, borderColor: '#00ff00', }, });
StyleSheet.create
的創(chuàng)建是可選的,但提供了一些關鍵優(yōu)勢。它通過將它們轉換為引用一個內部表的純數字,來確保值是不可變的和不透明的。通過將它放在文件的最后,也確保了它們?yōu)閼贸绦蛑粍?chuàng)建一次,而不是每一個 render 都創(chuàng)建。
所有的屬性名稱和值是工作在網絡中的一個子集。對于布局來說,React Native實現了 Flexbox。
所有的核心組件接受樣式屬性。
<Text style={styles.base} /><View style={styles.background} />
它們也接受一系列的樣式。
<View style={[styles.base, styles.background]} />
行為與 Object.assign
相同:在沖突值的情況下,從最右邊元素的值將會優(yōu)先,并且 falsy 值如 false
,undefined
和 null
將被忽略。一個常見的模式是基于某些條件有條件地添加一個樣式。
<View style={[styles.base, this.state.active && styles.active]} />
最后,如果真的需要,您還可以在render中創(chuàng)建樣式對象,但是這種做法非常不贊成。最后把它們放在數組定義中。
<View style={[styles.base, { width: this.state.width, height: this.state.width * this.state.aspectRatio }]} />
為了讓一個 call site 定制你的子組件的樣式,你可以通過樣式傳遞。使用 View.propTypes.style
和Text.propTypes.style
,以確保只有樣式被傳遞了。
var List = React.createClass({ propTypes: { style: View.propTypes.style, elementStyle: View.propTypes.style, }, render: function() { return ( <View style={this.props.style}> {elements.map((element) => <View style={[styles.element, this.props.elementStyle]} /> )} </View> ); } });// ... in another file ...<List style={styles.list} elementStyle={styles.listElement} />
最新的 CSS 屬性支持。
View 屬性
Image 屬性
Text 屬性
Flex 屬性
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: