欢迎来到码农权的博客 MaNongGeGe.|

React事件处理方法中this指向为undefined的四种解决方案

React事件处理方法中this指向为undefined的四种解决方案:

1. 定义事件后使用bind绑定this
    return (
      <div>
        <button onClick={this.clickHander.bind(this)}>Click</button>
      </div>
    )
2. 在构造函数内部声明this指向
  constructor() {
    super()
    this.clickHander = this.clickHander.bind(this)
  }
  clickHander () {
    console.log(this)
  }
  render () {
    return (
      <div>
        <button onClick={this.clickHander}>Click</button>
      </div>
    )
  }
3. 定义事件使用箭头函数
  render () {
    return (
      <div>
        <button onClick={() => this.clickHander()}>Click</button>
      </div>
    )
  }
4. 在开发中建议使用标准写法 在类中的事件回调采用箭头函数 state定义在组件实例下
const Hello = () => {
  state = {
      name: "Hello"
  }
  const clickHander = (e, msg) => {
    console.log(msg)
    e.preventDefault()
  }
  return (
    <div onClick={(e) => clickHander(e, "Hello")}>
      <a href="https://www.baidu.com" target={"_blank"}>函数 Go Baidu</a>
    </div>
  )
}

本文作者:HuangBingQuan

本文链接:https://www.cnblogs.com/bingquan1/p/16398415.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   HuangBingQuan  阅读(288)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 不将就 码农权
  2. 2 Bleeding Love 码农权
  3. 3 想你念你 码农权
Bleeding Love - 码农权
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

Not available