樣式管理
樣式是實(shí)現(xiàn)多端編譯的核心挑戰(zhàn)昂芜,因?yàn)?RN 端的樣式只是實(shí)現(xiàn)了 CSS 的一個(gè)子集,具體可參考 React-Native 樣式指南
首先因?yàn)槲沂荝N開(kāi)發(fā)者赔蒲,其次RN樣式兼容度是最低的泌神,所以我從RN環(huán)境出發(fā)然后再往各端轉(zhuǎn),我們首先要搞清楚RN在Taro上如何編寫樣式舞虱。
class 選擇器和style共用
普通編寫屬性使用class 選擇器
/* CustomComp.js */
import './index.scss'
export default class CustomComp extends Component {
render () {
return <Text className="red-text">樣式</Text>
}
}
/* MyPage.scss */
.red-text {
color: red;
}
傳遞屬性用style
export default class Index extends Component {
render () {
return (
<View className='index'>
<Text>Hello world!</Text>
<PageView />
<CustomView style={{backgroundColor:'#ff00ff'}} />
</View>
)
}
}
export default class CustomView extends Component {
render () {
return (
<View style={this.props.style} className='view_custom' onClick={() => alert('點(diǎn)擊了')}>
<Text>View居然支持RN點(diǎn)擊 還是不錯(cuò)的</Text>
</View>
)
}
}
轉(zhuǎn)譯后的樣式
css -> stylesheet 的轉(zhuǎn)換使用的是 css-to-react-native-transform
我們來(lái)看一下轉(zhuǎn)譯后的樣式代碼
// customview/index.js
import indexStyleSheet from "./index_styles";
var _styleSheet = indexStyleSheet;
let CustomView = class CustomView extends Component {
render() {
return <View style={[_styleSheet["view_custom"], this.props.style]} onClick={() => alert('點(diǎn)擊了')}>
<Text>View居然支持RN點(diǎn)擊 還是不錯(cuò)的</Text>
</View>;
}
};
export { CustomView as default };
//index_styles.js
import { StyleSheet, Dimensions } from 'react-native'
// 一般app 只有豎屏模式欢际,所以可以只獲取一次 width
const deviceWidthDp = Dimensions.get('window').width
const uiWidthPx = 375
function scalePx2dp (uiElementPx) {
return uiElementPx * deviceWidthDp / uiWidthPx
}
export default StyleSheet.create({
"view_custom": {
"paddingTop": scalePx2dp(38),
"paddingRight": scalePx2dp(38),
"paddingBottom": scalePx2dp(38),
"paddingLeft": scalePx2dp(38),
"backgroundColor": "#ff552e"
}
})
可見(jiàn)Taro應(yīng)用轉(zhuǎn)譯器將className轉(zhuǎn)化為StyleSheet,自動(dòng)生成了StyleSheet代碼,并將它和style拼在一起损趋。
有個(gè)疑問(wèn):因?yàn)閞n的style里面不能寫'150px'這種格式椅寺,默認(rèn)是dp,那么傳入的style不同端該如何控制值的單位呢
未完待續(xù)