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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM