样式布局
在duxapp中写样式为了兼容React Native,我们需要采取flex的布局方式,因此,为了和RN端获得一致的布局方式,默认会给小程序和h5的标签赋予默认样式,像下面这样
如果你仅依赖了 duxapp
这个基础模块,将不会有这些默认样式,因为 2505-04-16 的更新中将这些默认样式用到了独立的模块中
对于h5:
taro-view-core {
display: flex;
flex-direction: column;
position: relative;
border-style: solid;
border-width: 0;
}
input,
textarea,
taro-view-core {
box-sizing: border-box;
}
对于小程序:
view {
display: flex;
flex-direction: column;
position: relative;
border-style: solid;
border-width: 0;
}
input,
textarea,
view {
box-sizing: border-box;
}
- 在RN上
display
仅支持flex
和none
- 在RN上
position
支持relative
和absolute
- 在新版本的RN上开启新架构之后
position
也支持static
,但是他不是默认选项,所以,position的默认值还是会被设置为relative - RN上模型盒仅支持
border-box
样式编写规则
因为RN不存在选择器这一说法,因此在编写scss文件的时候,仅支持单一的class功能
/* 支持 */
.name {}
/* 下面的都不支持 */
.button.button_theme_islands {
font-style: bold;
}
img + p {
font-style: bold;
}
p ~ span {
color: red;
}
div > span {
background-color: DodgerBlue;
}
div span {
background-color: DodgerBlue;
}
为了实现兼容RN,需要使用BEM的规范书写样式,像下面这样
<View className="block">
<Text className="block__elem">文本</Text>
</View>
.block: {
background-color: DodgerBlue;
&__elem {
color: yellow;
}
}
这样的方式编写,如果内容过多会导致你的className过长,且修改起来也特别的费劲,更推荐使用下面的全局样式方式进行页面布局
在duxapp中使用的是scss,上面的样式文件是scss文件
使用全局样式布局
模块的 app.scss 提供了编写全局样式的地方,我们在基础模块(duxapp)的全局样式中导出了很多用于布局使用的全局样式,你可以在这个文档末尾查询到,用这些全局样式书写起来就类似于tailwindcss
一样
import { View, Text } from '@tarojs/components'
export const Test = () => {
return <View className='m-3 r-2 bg-white p-3 gap-3'>
<Text className='text-c1 text-s3 bold'>这是标题</Text>
<Text className='text-c3 text-s1 bold'>这是描述</Text>
</View>
}
就像这个示例一样,因为用bem编写本身className就会很长,我用差不多的长度就实现了样式布局,还省去了编写样式,且在修改的时候也不需要去修改对应的scss的内容,这样写起来也是非常的方便
全局样式中很多样式都是和主题相结合的,例如文字文字、背景颜色、边框颜色、字号等,可以在本文默认查看到
为何获得更好的编辑体验,需要在vscode中安装 SCSS Everywhere
插件,他能识别到全局样式并给出编写提示
当然全局样式并不能覆盖所有的场景,你可以结合其他方案来完善:
- 在自己的模块使用全局样式完善
- 继续写scss
- 写style补全不支持的样式
这里演示下使用style完善,大部分不支持的样式基本都和尺寸相关,例如 width
height
等,样式里面没办法定义的尺寸完全能满足要求,就可以使用style补全
import { View, Text } from '@tarojs/components'
import { px } from '@/duxapp'
export const Test = () => {
return <View className='m-3 r-2 bg-white p-3 gap-3'>
<Text className='text-c1 text-s3 bold'>这是标题</Text>
<Text className='text-c3 text-s1 bold'>这是描述</Text>
<Image className='w-full' style={{ height: px(240) }} />
</View>
}
px方法是 Taro.pxTransform 的简写,为了看起来更简洁一些,并且做了一些处理
使用duxui
使用样式编辑页面还是会很麻烦,要写很多的样式,那么可以在结合使用duxui模块提供的大量ui组件,还能将写代码的速度提升一个层次
前往下一章节查看 使用UI库