【问题标题】:How does bind work inside react classes and JSX events ? [duplicate]绑定如何在反应类和 JSX 事件中工作? [复制]
【发布时间】:2017-06-10 03:16:57
【问题描述】:

我在这里试图了解我评论的绑定的必要性..

class Toggle extends Component {

    constructor(props){
    super(props);

    //this.handleClick = this.handleClick.bind(this);
}


handleClick() {

    console.log(this); 

}


render() {
    return (
        <button onClick={this.handleClick}>
            ...
        </button>
    );
}

}

当我在handleClick 中记录this 时,它会输出null ..

我知道需要绑定才能将handleClick 方法连接到Toggle 对象..

但是日志现在不应该查找handleClick 在哪里调用或调用,以便输出全局对象吗?

或者它是否应该在onClick 中查找调用handleClick 的“什么”,这是另一个this 引用Toggle 对象以便输出它?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

如果你在Toggle中绑定handleClick,当我尝试在状态中记录value属性时,它确实会将方法绑定到类,如下所示。否则会抛出错误,您可以在浏览器控制台中检查它(不在代码 sn-p 中)。

我不是 100% 确定为什么未绑定 handleClick 中的 console.log(this) (this post 的 OP 有类似问题)返回未定义,但我猜可能是它指的是 null组件,因为它的 undefined 值为 this

class Toggle extends React.Component {
  constructor(props){
    super(props);
    this.state = { value: 'hi' }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log(this.state.value); 
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          Hello
        </button>
        <NullComponent />
      </div>
    );
  }
}

let NullComponent = () => { 
  console.log('calling from null component ', this);
  return null; 
}

ReactDOM.render(<Toggle />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2015-12-28
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多