taro常用的一些功能

本文介绍了如何在Taro小程序中实现打电话功能、弹窗获取用户位置、使用Map组件进行导航、处理图片上传、动画效果和跳转外部H5页面,以及录音功能的使用。
摘要由CSDN通过智能技术生成

1.打电话

Taro.makePhoneCall({
        phoneNumber:that.state.tell,
        success:function(){
        }
      })

2.弹窗获取位置-->获取本人地理位置

// 弹窗
Taro.showModal({
        content: '即将前往设置,允许小程序获取您的位置信息',
        showCancel:false,
        success: function (res) {
          if (res.confirm) {
            // 查询本机设置
            Taro.openSetting({
              success(reso) {
                console.log(reso)
                 // 看看本机有没有授权
                if (reso.authSetting["scope.userLocation"]) {
                    // 清缓存
                  Taro.removeStorageSync("userLocation");
                }
                // 获取位置
                Taro.getLocation({
                  type: 'wgs84',
                  success: function (res) {
                    console.log(res)
                    putKey('longitude',res.longitude)
                    putKey('latitude',res.latitude)
                    // 成功就跳转
                    Taro.navigateTo({
                      url:url
                    })
                  },
                  fail:function(err){
                    console.log(err)
                    showError('未获取位置信息,路线规划失败')
                  }
                })
              },
              fail(err){
                console.log(err)
              }
            });
          } 
        }
      })

 3.有位置信息,需要按照给的地址名,还有经纬度进行跳转

第一步需要有Map标签

 <Map id='myMap' markers={mar} longitude={this.state.longitude} latitude={this.state.latitude}  className='map' />

第二步进行跳转

open(item){
    const mapCtx = Taro.createMapContext('myMap');
    mapCtx.openMapApp({
      latitude: parseFloat(item.latitude),
      longitude: parseFloat(item.longitude),
      destination: item.stationName,
      success:function(e){console.log("openResult1",e)},
      fail:function(e){console.log("openResult2",e)},
      complete:function(e){console.log("openResult3",e)},
    })
    
  }

下边是一个地图展示站点,有相应的站点以及点击每个站点左边进入详情右边进行到第三方导航

import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image,Map } from '@tarojs/components'
import { AtIcon, AtGrid, AtAvatar  } from 'taro-ui'
import { getKey,putKey } from '@/src/utils/storage-utils'
import { showError } from '@/src/utils/loading-utils'
import {wxLogin,listByDistance } from '@/src/api/api'
import LoginView from '@/src/components/loginView/index'
import './index.less'
let mar = []
class OtherServeSite extends Component {

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '',
    navigationStyle: 'default',
    navigationBarBackgroundColor: '#FFFFFF',
    navigationBarTextStyle: 'black',
    backgroundColorTop: "#FFFFFF"
  }

  constructor (props) {
    super(props)
    this.state = {
      list:[],
      none:require('@/src/assets/images/none.png'),
      markers:[],
      latitude:'',
      longitude:'',
      title:''
    }
  }

  // componentWillReceiveProps () {}

  // componentWillUnmount () {}

  componentDidMount(){
    
  }

  // componentDidShow () {}

  // componentDidHide () {}

  // 下拉刷新
  onReachBottom() {
    var param = {
      latitude:getKey('latitude'),
      longitude: getKey('longitude'),
      types:7
    }
    console.log('param',param)
    listByDistance(param).then(res=>{
      console.log(res)
      
      if(res.code == 200){
        this.setState({
          list:res.rows,
          markers:res.rows,
        })
      }else{
        showError(res.msg)
      }

    })
  }

  componentDidShow() {
    var param = {
      latitude:getKey('latitude'),
      longitude: getKey('longitude'),
      types:7
    }
    console.log('param',param)
    listByDistance(param).then(res=>{
      console.log(res)
      if(res.code == 200){
        var list  = res.rows
        for(var j=0; j<list.length;j++){
          mar.push({
              'id': list[j].id,
              'latitude':list[j].latitude,
              'longitude':  list[j].longitude,
              'width': 30,  //图片显示宽度
              'height': 30,//图片显示高度
              'title': list[j].stationName,
              'label': {      //标记的提示文字的样式
               'color':'#e41111',
                'content': list[j].stationName,//提示内容
                
            }
          })
       
        }
        
        console.log(mar,9999999)
        getKey('markers',mar)
        this.setState({
          latitude:mar[0].latitude,
          longitude:mar[0].longitude,
          title:mar[0].title
        })
        let arr = []
        for(var i=0; i<list.length; i++){
          arr.push(list[i])
        }
        this.setState({
          list:arr
        })
        // if(res.rows.length<=3){
        //   this.setState({
        //     list
        //   })
        // }else{
        //   let arr = []
        //   for(var i=0; i<3; i++){
        //     arr.push(list[i])
        //   }
        //   this.setState({
        //     list:arr
        //   })
        // }
        
      }else{
        showError(res.msg)
      }

    })

  }
  
  open(item){
    const mapCtx = Taro.createMapContext('myMap');
    mapCtx.openMapApp({
      latitude: parseFloat(item.latitude),
      longitude: parseFloat(item.longitude),
      destination: item.stationName,
      success:function(e){console.log("openResult1",e)},
      fail:function(e){console.log("openResult2",e)},
      complete:function(e){console.log("openResult3",e)},
    })
    
  }
  detail(item){
    Taro.navigateTo({
      url:'/pages/statusMapDetail/index?id='+item.id
    })
  }

  render () {
    
    const { otherServeGridList,list } = this.state
    console.log(mar,909090)
    return (
      <View className='user-container'>
        <View className='near'>
          <View>
          <Image className='nearImg' src={require('@/src/assets/user/address-icon.png')} />
          </View>
          <View>其他服务站点</View>
        </View>
        <View className='scrollBox'>
        {
            list.length>0 ? <View>
              {
            list.map((item,index) => {
              return (
                <View  key={item.id}  className='site-item' >
                  <View  onClick={this.open.bind(this,item)} className='daohang'>
                    <View>
                    <Image className='navigation' src={require('@/src/assets/user/navigation.png')} />
                    </View>
                    <View>导航</View>
                  </View>
                  <View  className='left'  onClick={this.detail.bind(this, item)} >
                    <View className='flex'>
                      <View  className='name' >{item.stationName}</View>
                      {
                        index == 0 &&<View className='jin'>最近</View>
                      }
                      
                    </View>
                    
                    {/* <View className='tell' >{item.contactPhone}</View> */}
                    <View className='address' >{item.stationLocation}</View>
                  </View>
                  
                </View>
              )
            })
          }
            </View>:<View className='none'>
            <View  className='img' >
              <Image src={none} className='pic'></Image>
            </View>
            <View className='noText'>暂无数据</View>
          </View>
          }
        </View>
          
        <View className='map'>
          <Map id='myMap' markers={mar} longitude={this.state.longitude} latitude={this.state.latitude}  className='map' />
        </View>
      </View>
    )
  }
}

export default OtherServeSite

 4.上传功能

背景:需求是最多三张图片,但是接口每次只能上传一张

 第一步:AtImagePicker组件上去

<AtImagePicker count={3} multiple={true} files={this.state.files} onChange={this.onImg.bind(this)} />

第二步 onImg方法

  onImg (files,method,index) {
    if(files.length>3){
      Taro.showToast({
        title: '最多上传3张图片',
        icon:'none',
        duration: 2000
      })
      return false
    }

    for(let i=0; i<files.length; i++){
      if( 2097152 -files[i].file.size <0 ){
        Taro.showToast({
          title: '图片不能大于2M',
          icon:'none',
          duration: 2000
        })
        return false
      }
    }
    

    this.setState({
      files,
    })
    let url =''
    
    if(files.length == 1){
      url = files[0].url
    }
    if(files.length == 2){
      url = files[1].url
    }
    if(files.length == 3){
      url = files[2].url
    }

    if(method == 'add'){
      Taro.showLoading({
        title: '上传中',
        mask:true
      })
      Taro.uploadFile({
        url: uploadUrl+'/wxapi/upload',  //仅为示例,非真实的接口地址
        filePath: url,
        name: 'file',
        header: {
          'content-type': 'application/json',
          'openid': getKey('openId')
        },
        success (res){
          Taro.hideLoading()
          pics.push(JSON.parse(res.data).url)
        },
        fail(err){
          Taro.hideLoading()
        }
      })

    }

    if(method == 'remove'){
      pics.splice(index, 1)
    }
    console.log('获取的files',files)
    return files
}

5.动画效果Taro

第一步:加载时的钩子函数调用动画函数

第二步:写动画函数

第三步:render中的标签引用

import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import './index.scss'
 
export default class AnimationExample extends Taro.Component {
  constructor(props) {
    super(props)
    this.state = {
      animationData: null,
    }
  }
 
  componentDidMount() {
    this.startAnimation()
  }
 
  startAnimation = () => {
    const animation = Taro.createAnimation({
      duration: 300,
      timingFunction: 'ease',
    })
 
    this.animation = animation
 
    animation.opacity(1).step()
    this.setState({ animationData: animation.export() })
  }
 
  render() {
    return (
      <View className="animation-container">
        <View
          className="animated-view"
          style={this.state.animationData}
        >
          我是一个淡入的动画
        </View>
      </View>
    )
  }
}

 6.Taro小程序跳转其他平台的H5页面怎么做?

1.首先在pages写一个承载H5的页面;

2.然后在app.js里边进行设置相关的路由;

3.在微信的小程序开发后台进行业务域名配置,并且部属时候把校验文件放在域名根目录。

import Taro, { Component } from '@tarojs/taro'
// 引入 WebView 组件
import { WebView } from '@tarojs/components'

class WebviewComponent extends Component {
  render () {
    return (
      <WebView src='https://mp.weixin.qq.com/'  />
    )
  }
}

export default WebviewComponent;

7.录音功能

import Taro, { Component } from '@tarojs/taro'
import { View, Button } from '@tarojs/components'
class Recording extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isRecording: false,
      audioSrc: ''
    };
  }
  startRecord() {
    this.setState({isRecording: true});
    
    Taro.startRecord({
      success: (res) => {
        console.log(res.tempFilePath); // 打印录音文件路径
        this.setState({audioSrc: res.tempFilePath}); // 设置state保存录音文件路径
      },
      fail: () => {
        console.log('start record failed');
      }
     })
   }
   stopAndPlay() {
     const { audioSrc } = this.state;
     
     if (audioSrc) { 
       const audioContext = Taro.createInnerAudioContext()
       audioContext.src = audioSrc; // 设置src为刚才保存的tempFilePath
      
       audioContext.play();
      
       audioContext.onEnded(() => {
         console.log('audio play ended')
         audioContext.destroy(); // 销毁上下文对象以释放内存资源
       })
     }
     
     this.setState({isRecording:false})
     Taro.stopRecord();
   }
   render() {
     return (
       <View>
         <Button onClick={this.startRecord.bind(this)}>开始</Button>
         <Button disabled={!this.state.isRecording} onClick={this.stopAndPlay.bind(this)}>停止并播放</Button>
          {/* 渲染用于测试的组件 */}
          <View>{this.state.audioSrc}</View> 
        </View>
      )
   }
}
export default Recording;

 

今天周六,下午写一些感觉很好,后续继续添加,希望对用taro框架的童鞋有些帮助,继续加油中

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值