【问题标题】:Why "this" is null inside the React function invoked from HTML element [duplicate]为什么“this”在从 HTML 元素调用的 React 函数中为空 [重复]
【发布时间】:2018-06-29 00:13:36
【问题描述】:

我有一个简单的 React 代码,如下所示:

export class TodoList extends Component {

  constructor(props) {
    super(props)
    console.log(this)
  }

  addTask() {
    // why is this null 
    console.log(this.textInput)
  }



  render() {
    return (
      <div>
        <input type="text" ref={(input) => {this.textInput = input}}  />
        <button onClick={this.addTask}>Add New Task</button>

        <h6>Pending Tasks</h6>
        <PendingTaskList />

      </div>
    )
  }
}

在 addTask 函数中,“this”的值始终为空。我知道我可以通过绑定它来解决这个问题,但我的问题是为什么它首先是空的。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    它为空,因为this 不再引用该类。避免这种情况的最好方法是使用箭头函数。

    来自doc:

    箭头函数不会创建自己的 this 上下文,所以 this 有 它的原始含义来自封闭的上下文。

    addTask = () => {
        console.log(this.textInput)
    }
    

    【讨论】:

    • 但是在函数addTask里面“this”是空的
    • 不是指函数,而是指绑定的对象。在这种情况下,它是未绑定的。您需要使用 this.addTask = this.addTask.bind(this) 将其绑定到构造函数中的实例,如果您使用的是 babel,请使用 experimental public class fields syntax。
    • 为什么没有绑定?通常 HTML 元素被绑定到 window 对象,但它是板载的,因为这是虚拟 DOM。
    • 啊我现在明白了。类方法默认不绑定。
    猜你喜欢
    • 1970-01-01
    • 2013-09-09
    • 2012-02-20
    • 1970-01-01
    • 2019-03-10
    • 2016-04-06
    • 2016-10-17
    • 2020-03-08
    • 2014-03-15
    相关资源
    最近更新 更多