【问题标题】:Why is the this keyword inside clickHandler undefined?为什么clickHandler中的this关键字未定义?
【发布时间】:2021-09-15 15:52:42
【问题描述】:

当我对 this 关键字的实现感到困惑时,我正在关注有关 eventHandling 的 YouTube 教程。

在下面的代码中,clickHandler 函数中的 this 关键字给出了 undefined 的值。讲师说这是因为 JavaScript 就是这样工作的。但是当我在网上搜索时,我发现 this 关键字在类的函数中使用时,指向对象本身。

这可能是一个愚蠢的问题,但由于我是 JavaScript 新手,任何帮助都将不胜感激

class EventBind extends Component {
  constructor(props) {
    super(props);

    this.state = {
      message: "Hello",
    };
  }

  clickHandler() {
    // this.setState({
    //   message : 'Goodbye'
    // })
    console.log(this);
  }

  render() {
    return (
      <div>
        <div>{this.state.message}</div>
        <button onClick = {this.clickHandler}>Click</button>
      </div>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs object event-handling this


    【解决方案1】:

    这是因为您没有将clickHandler 绑定到this。 试试下面的代码

    class EventBind extends Component {
      constructor(props) {
        super(props);
        this.clickHandler = this.clickHandler.bind(this);
        ...
    
      }
      clickHandler() {
        ...
      }
      ...
      
    }
    

    查看这里了解更多信息:https://reactjs.org/docs/faq-functions.html

    【讨论】:

    猜你喜欢
    • 2020-05-04
    • 2018-08-17
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多