组件样式
组件的外部样式和全局样式
样式使用
自定义组件对应的样式文件,只对该组件内的节点生效。编写组件样式时,需要注意以下几点:
- 组件和引用组件的页面不能使用
id 选择器(#a
) 、属性选择器([a]
)和标签名选择器,请改用class 选择器。 - 组件和引用组件的页面中使用后代选择器(
.a .b
)在一些极端情况下会有非预期的表现,如遇,请避免使用。 - 子元素选择器(
.a > .b
)只能用于View
组件与其子节点之间,用于其他组件可能导致非预期的情况。 - 继承样式,如
font
、color
,会从组件外(父组件)继承到组件内。但是引用组件时在组件节点上书写的className
无效。 - 除继承样式外,
app.scss
中的样式、组件所在页面的样式,均对自定义组件无效。
#a {
} /* 在组件中不能使用 */
[a] {
} /* 在组件中不能使用 */
button {
} /* 在组件中不能使用 */
.a > .b {
} /* 除非 .a 是 view 组件节点,否则不一定会生效 */
除此以外,组件可以指定它所在节点的默认样式,使用
/* 该自定义组件的默认样式 */
:host {
color: yellow;
}
外部样式类
如果想传递样式给引用的自定义组件,以下写法(直接传递 className
)不可行:
/* CustomComp.js */
export default class CustomComp extends Component {
static defaultProps = {
classname: 'CGDataVis Series',
}
render () {
return <View className={this.props.className}>这段文本的颜色不会由组件外的 class 决定</View>
}
}
/* MyPage.js */
export default class MyPage extends Component {
render () {
return <CustomComp className="red-text" />
}
}
/* MyPage.scss */
.red-text {
color: red;
}
取而代之的,需要利用 externalClasses
定义段定义若干个外部样式类。这个特性从小程序基础库版本 1.9.90 开始支持。
/* CustomComp.js */
export default class CustomComp extends Component {
static externalClasses = ['my-class']
render () {
return <View className="my-class">这段文本的颜色由组件外的 class 决定</View>
}
}
/* MyPage.js */
export default class MyPage extends Component {
render () {
return <CustomComp my-class="red-text" />
}
}
/* MyPage.scss */
.red-text {
color: red;
}
全局样式类
使用外部样式类可以让组件使用指定的组件外样式类,如果希望组件外样式类能够完全影响组件内部,可以将组件构造器中的 options.addGlobalClass
字段置为 true
。这个特性从小程序基础库版本 2.2.3 开始支持。
/* CustomComp.js */
export default class CustomComp extends Component {
static options = {
addGlobalClass: true
}
render () {
return <View className="red-text">这段文本的颜色由组件外的 class 决定</View>
}
}
/* 组件外的样式定义 */
.red-text {
color: red;
}
设计稿及尺寸单位
在
如果你希望部分
const config = {
projectName: 'myProject',
date: '2018-4-18',
designWidth: 640,
....
}
目前
const deviceRatio = {
640: 2.34 / 2,
750: 1,
828: 1.81 / 2,
};
建议使用750px
375
,不在以上三种之中,那么你需要把 designWidth
配置为 375
,同时在 deviceRatio
中添加换算规则如下:
{
designWidth: 375,
deviceRatio: {
'375': 1 / 2,
'640': 2.34 / 2,
'750': 1,
'828': 1.81 / 2
}
}
在编译时,
Taro.pxTransform(10); // 小程序:rpx,H5:rem