第一次使用Taro,把遇到的坑罗列一遍,给后继踩坑者做参考吧。
开发环境
- taro版本:v1.3.0-beta.5
- nodejs版本:v8.11.4
踩过的坑
- 1. 实现小程序的slot的功能,开发工具翻译的wxml结果是slot内容和组件是同级,而非嵌套关系。
- 2. 使用externalClasses,为组件定义外部样式失效。
- 3. 在component文件内使用“函数式组件”出错了
1. 实现小程序的slot的功能,开发工具翻译的wxml结果是slot内容和组件是同级,而非嵌套关系。《Children 与组合》Taro官方文档
这是小程序开发工具的bug, 最后视图窗口显示是正确的,实际是正确的,github.com/NervJS/taro…
编译前组件代码
// component.js
<View className={'must-login-btn ' + className} hoverClass='btn-hover' onClick={this.onClick}>
{
!userToken
? <Button className='user-info-btn' openType='getUserInfo' onGetuserinfo={handleGetUserInfo} />
: ''
}
{ this.props.children }
</View>
复制代码
// page.js
<MustLoginBtn className='scan-btn' onClick={this.doScan}>
<View className='scan-btn-inner'>
<View className='scan-icon' />
<Text className='btn-text'>扫小程序码</Text>
</View>
</MustLoginBtn>
复制代码
开发工具中看到的wxml如下:
2. 使用externalClasses,为组件定义外部样式失效。《组件模板和样式》小程序官方文档,《组件的外部样式和全局样式》Taro官方文档
使用全局样式类,放弃使用externalClasses。
在component文件内设置addGlobalClass: true
, 同时使用props获取外部定义的className
在page.js文件内使用自定义组件式时,设置className
属性
在page.scss样式文件设置外部样式
/* CustomComp.js */
export default class CustomComp extends Component {
// 设置全局样式
static options = {
addGlobalClass: true
}
// 使用prop设置自定义className
static defaultProps = {
className: ''
}
render () {
return <View className={this.props.className}>这段文本的颜色不会由组件外的 class 决定</View>
}
}
复制代码
/* MyPage.js */
import './MyPage.scss';
export default class MyPage extends Component {
render () {
return <CustomComp className="red-text" />
}
}
复制代码
/* MyPage.scss */
.red-text {
color: red;
}
复制代码
3. 在component文件内使用“函数式组件”出错了
函数的命名必须以 render 开头,render 后的第一个字母需要大写。《类函数组件》Taro官方文档
- 错误表现:
这个不应该算是坑,是阅读文档不够深刻。
4.更新中……
转载于:https://juejin.im/post/5cf63166f265da1bd6059104