Taro react事件传参 路由传参

react语法事件传参

事件处理

  1. 事件传递 无参数
  //事件
  jumpToPage(){
        console.log(this)
   }
  //按钮点击onclick触发事件
 <AtButton type="primary" circle onClick={this.jumpToPage}> 点击跳转 </AtButton>

打印:{type: "primary", circle: true, children: "点击打印log", size: "normal", onClick: ƒ, …}

经过打印 发现jumpToPage方法中的this代表是AtButton这个对象本身,而不是页面对象,所有这里需要注意了,如果需要让this代表当前页面对象,可以使用ES6箭头函数语法

解决如上问题,使用下面两种方式中的任意一种

  //方法1
  jumpToPage = (event)=>{
        console.log(this)
       console.log(event)
   }
  //按钮点击onclick触发事件
 <AtButton type="primary" circle onClick={this.jumpToPage.bind(this)}> 点击跳转 </AtButton>
 //方法2
  jumpToPage(){
        console.log(this)
   }
  //按钮点击onclick触发事件
 <AtButton type="primary" circle onClick={()=>this.jumpToPage()}> 点击跳转 </AtButton>

打印:Index {props: {…}, context: {…}, refs: {…}, updater: {…}, jumpToPage: ƒ, …}

  1. 事件传递参数

    参数传递也有两种方式实现 实现原理基于上面两种方法

   const params = 'abc'
  //方法1
  jumpToPage = (params,m,event)=>{
         //经过测试发现 event是最后一个参数
        console.log(params,m,event)
   }
  //按钮点击onclick触发事件
 <AtButton type="primary" circle onClick={this.jumpToPage.bind(this,params,'mm')}> 点击跳转 </AtButton>
打印:`abc mm MouseEvent {isTrusted: true, screenX: 305, screenY: 410, clientX: 261, clientY: 272, …}`
 //方法2
  jumpToPage(){
        console.log(this)
   }
  //按钮点击onclick触发事件
 <AtButton type="primary" circle onClick={()=>this.jumpToPage(params,mm)}> 点击跳转 </AtButton>

打印:`abc mm`

路由处理

  1. 正向传值

    A页面通过路由跳转到B页面 同时传参到B页面

import Taro from '@tarojs/taro'
  itemClick = (id) => {
    Taro.navigateTo({ url: `/pages/index2/index2?id=${id}` })
  }      

B页面接受传递参数
import { getCurrentInstance } from '@tarojs/taro'
const id = getCurrentInstance().router.params.id
console.log(id)
  1. 反向传值
1. 父控件传参控制子控件显示
 <List items={datas} ></List>
2.子控件中通过props拿到items参数
const { items } = this.props
3.子控件通过items内容刷新数据显示
 render() {
        const { items } = this.state
        return (
            <View>
                {
                    items.map((res, index) => {
                        return <View key={index}>
                            <AtButton onClick={()=>this.onClick(index)}>{res}</AtButton>
                        </View>
                    })
                }
            </View>
        )
    }
4. 在子控件中实现点击事件 通过this.props将onTap事件传递出去 后面index为参数
 onClick = (index)=>{
        console.log(index)
        //把事件传递出去
        this.props.onTap(index)
    }
5. 在父控件中监听 onTap事件 并接收index参数
 <List items={datas} onTap={(index) => this.onTap(index)}></List>
 onTap = (e) => {
    console.log(e)
  }
最后打印出来的e = index