taro中微信小程序冒泡事件處理


這是我的第一個微信小程序taro項目,從來都不知道什么叫冒泡事件,出錯了就不知道這么搞,主要是前端也只有一個人負責,第一次使用taro,所以走了很多的坑

什么叫冒泡事件呢?

  當然更明顯的在網上很多,但是自己理解的才是最好。理解:父級組件中有點擊事件,子組件中也有點擊事件,當點擊子組件的綁定的點擊事件,e(事件)會向上去調用了父組件的點擊事件,所以這不是我們想要的,所以我們必須阻止事件冒泡。下面是我親測有效的,官網的試過但是報了undefind。

 函數:
toPopDeitail (type, refrenceInfo, aliasName, nums) { // 首頁彈窗跳轉到相應的頁面
    //type:00-表示商品,01-表示商品分類,02-優惠券,03-大轉盤,04-砸金蛋,05-公告信息,06-公告關聯文章
    //refrenceInfo:關聯分類code、商品ID、優惠券ID
    // debugger
    //e.stopPropagation()阻止冒泡
    // console.log(nums)
    if (type === '00') {
      Taro.navigateTo({
        url: '/pages/product/index?id=' + refrenceInfo
      })
    }
}

頁面調用:通過匿名函數
<View
                                className='home-popup-body'
                                onClick={e => { e.stopPropagation(); this.toPopDeitail(items.type, items.refrenceInfo, items.aliasName, num) }}
                              >
                                <Image className='home-popup-body-img' src={items.image}></Image>
                              </View>
View Code

 

官網:https://taro-docs.jd.com/taro/docs/event/
Version: 3.x

事件處理

Taro 元素的事件處理和 DOM 元素的很相似。但是有一點語法上的不同:

Taro 事件綁定屬性的命名采用駝峰式寫法,而不是小寫。 如果采用 JSX 的語法你需要傳入一個函數作為事件處理函數,而不是一個字符串 (DOM 元素的寫法)。 例如,傳統的微信小程序模板:

<button onclick="activateLasers">
Activate Lasers
</button>

Taro 中稍稍有點不同:

<button onClick={this.activateLasers}>
Activate Lasers
</button>

在 Taro 中另一個不同是你不能使用 catchEvent 的方式阻止事件冒泡。你必須明確的使用 stopPropagation。例如,阻止事件冒泡你可以這樣寫:

class Toggle extends Component {
constructor (props) {
super(props)
this.state = {isToggleOn: true}
}
 
onClick = (e) => {
e.stopPropagation()
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}))
}
 
render () {
return (
<button onClick={this.onClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
)
}
}

向事件處理程序傳遞參數#

通常我們會為事件處理程序傳遞額外的參數。例如,傳入欲刪除行的 id

<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

當你通過 bind 方式向監聽函數傳參,在類組件中定義的監聽函數,事件對象 e 要排在所傳遞參數的后面。

class Popper extends Component {
constructor () {
super(...arguments)
this.state = { name:'Hello world!' }
}
 
// 你可以通過 bind 傳入多個參數
preventPop (name, test, e) { //事件對象 e 要放在最后
e.stopPropagation()
}
 
render () {
return <Button onClick={this.preventPop.bind(this, this.state.name, 'test')}></Button>
}
}

使用匿名函數#

自 v1.2.9 開始支持

注意:在各小程序端,使用匿名函數,尤其是在 循環中 使用匿名函數,比使用 bind 進行事件傳參占用更大的內存,速度也會更慢。

除了 bind 之外,事件參數也可以使用匿名函數進行傳參。直接寫匿名函數不會打亂原有監聽函數的參數順序:

class Popper extends Component {
constructor () {
super(...arguments)
this.state = { name: 'Hello world!' }
}
 
render () {
const name = 'test'
return (
<Button onClick={(e) => {
e.stopPropagation()
this.setState({
name
})
}}>
{this.state.name}
</Button>
)
}
}
 
 

注意: 使用通過 usingComponents 的第三方組件不支持匿名函數


免責聲明!

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



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