Fork me on github

Taro 采坑日常

 组件事件传参只能在类作用域下的确切引用(this.handleXX || this.props.handleXX),或使用 bind。

  组件中点击事件如下

//  组件
<AtListItem 
  key={i}
  isSwitch 
  switchIsCheck={ true } 
  onSwitchChange={ (e) => this.handleSwitchChange(e, i) }
 />

 // 方法
handleSwitchChange = (e, i) => {
  console.log('e :', e)
  console.log('i :', i)
}

  在H5端正常运行, 在小程序端时抛出了异常:

// Error: 组件事件传参只能在类作用域下的确切引用(this.handleXX || this.props.handleXX),或使用 bind。

  写过 react 的同学都知道 这种写法在日常比较常见的, 这个异常 一开始 也是让我百思不得解

  最终解决方案如下:

  

//  组件
<AtListItem 
  key={i}
  isSwitch 
  switchIsCheck={ true } 
  onSwitchChange={ this.handleSwitchChange.bind(this, i) }
 />

 // 方法
handleSwitchChange = (i, e) => {
  console.log('i :', i)
  console.log('e :', e)
  // 这里的参数顺序有所不同
     // 第一个参数为组件方法中 传入的索引值
  // 第二个参数为 this, 这个参数参数 在bind 时 不需要传入
}

  这种写法 在 H5 已经 小程序端 输入达成统一, 此坑过~

posted @ 2019-05-26 17:33  vanst  阅读(619)  评论(0编辑  收藏  举报