这是我的第一个微信小程序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>
官网: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
的第三方组件不支持匿名函数