Taro踩坑记之React-Native样式篇

2019-07-28  本文已影响0人  LaxusJ

样式管理

样式是实现多端编译的核心挑战,因为 RN 端的样式只是实现了 CSS 的一个子集,具体可参考 React-Native 样式指南

首先因为我是RN开发者,其次RN样式兼容度是最低的,所以我从RN环境出发然后再往各端转,我们首先要搞清楚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('点击了')}>
        <Text>View居然支持RN点击 还是不错的</Text>
      </View>
    )
  }
}

转译后的样式

css -> stylesheet 的转换使用的是 css-to-react-native-transform

我们来看一下转译后的样式代码

// 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('点击了')}>
        <Text>View居然支持RN点击 还是不错的</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"
  }
})

可见Taro应用转译器将className转化为StyleSheet,自动生成了StyleSheet代码,并将它和style拼在一起。

有个疑问:因为rn的style里面不能写'150px'这种格式,默认是dp,那么传入的style不同端该如何控制值的单位呢

未完待续

参考
使用 Taro 编译小程序 + H5 + React Native 的最佳实践

上一篇下一篇

猜你喜欢

热点阅读