Taro开发注意事项

推荐命名

  1. 普通js/ts文件, 命名: util.js, util_helper.js
  2. 组件文件(大驼峰+jsx后缀): PayResult.jsx, CouponCenter.jsx

CSS标签选择器(View,Text)不生效

  • 支付宝小程序不生效, 推荐用类名
// 支付宝端无效
View{
  color:#000
}

// ok
.box{
  color:#000
}

轮播组件绑定事件无效

  • 支付宝端: SwiperItem标签绑定onClick事件无效, 必须绑在内部的View或Image标签上
// 绑定事件无效
<Swiper>
  {swiperList.map((item) => {
    return (
      <SwiperItem key={item.cardPackagePartnerId} onClick={tapBanner.bind(
            this,
            item.cardPackagePartnerId
          )}>
        <Image src={item.cardPackageImage} />
      </SwiperItem>
    );
  })}
</Swiper>

// ok
<Swiper>
  {swiperList.map((item) => {
    return (
      <SwiperItem key={item.cardPackagePartnerId} >
        <Image
          onClick={tapBanner.bind(
            this,
            item.cardPackagePartnerId
          )}
          src={item.cardPackageImage}
        />
      </SwiperItem>
    );
  })}
</Swiper>

build打包后背景图错乱

  • 问题: build打包会进行代码压缩合并, 将不同选择器相同的属性background-size: contain;提取合并到一起, 但是合并后的代码确放在background之前, 导致background复合属性覆盖掉了background-size属性
  • 推荐: 联调测试阶段采用build打包, 避免使用dev打包
/* 推荐 */
.box{
  background-image: url("https://19ego.cn/home/home-default.png");
  background-repeat: no-repeat;
  background-size: contain;
}

/* 不推荐 */
.box{
  background: url("https://19ego.cn/home/home-default.png") no-repeat;
  background-size: contain;
}

JSX遍历

  • JSX中遍历数组只能使用map

JSX遍历时: 事件传参不支持对象字面量

react-hooks组件中没有复现

const article = [{id:1, title:"标题1"}, {id:2, title:"标题2"}]

// 报错
render(){
  return (
    <View>
      article.map((item,index) => {
        // 报错: 不允许传字面量对象
        return <View onClick={this.doPay.bind(this, {title:item.title})}>{item.name}</View>
      })
      )
    </View>
}

/// 解决
render(){
  return (
    <View>
      article.map((item,index) => {
        // 变量
        const obj = {
          title:item.title
        }
        return <View onClick={this.doPay.bind(this, obj)}>{item.name}</View>
      })
      )
    </View>
}

taro打包出错

  • 问题: 命令行工具@tarojs/cli与项目依赖的版本不一致
  • 解决: 升级@tarojs/cli时注意升级项目依赖, 保持taro工具与项目依赖的版本一致