【问题标题】:Why should i need the bind when using event in React为什么在 React 中使用事件时需要绑定
【发布时间】:2018-12-18 03:14:54
【问题描述】:

有人可以向我解释为什么我在使用事件时需要使用绑定this.handleClick = this.handleClick.bind(this); 吗?

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

为什么要定义'this'的值?

class Person {
    constructor(name, yearOfBirth) {
        this.name = name;
        this.yearOfBirth = yearOfBirth;
    }

    calculateAge() {
        console.log(this);
    }
}

const john = new Person('John', 1993);
john.calculateAge();

但是点击时'this'的值是不确定的?

function ActionLink() {
    function handleClick(e) {
      e.preventDefault();
      console.log('The link was clicked.');
      console.log(this);
    }

    return (
      <a href="#" onClick={handleClick}>
        Click me
      </a>
    );
}

ReactDOM.render(
    <ActionLink />,
    document.getElementById('root')
);

【问题讨论】:

  • 你应该把这个问题分成两个问题。
  • 将handleClick() 函数更改为this.handleClick() 并使用this.handleClick() 调用。你认为“这个”是什么?
  • 所以在 react 组件中你可以使用handleClick = () =&gt; { 来声明this 方法以避免使用bind

标签: javascript reactjs


【解决方案1】:

this 始终在调用函数的上下文中执行。

因此,当 React 组件呈现时,元素和事件处理程序将附加到 DOM 并在 DOM 的上下文中执行。所以如果不将方法绑定到组件,就不能在方法内部使用this

// this will be window and window.setState will be undefinedd
this.setState(state => ({
  isToggleOn: !state.isToggleOn
}));

当您将方法绑定到组件时,this 将在组件的上下文中执行,您将能够调用 .setState

有趣的是,如果你的方法不使用任何this 调用,即使你不绑定也不会有任何问题。

正如 quirimmo 在 cmets 中指出的那样,在严格模式下,默认情况下这将是 undefined,即使没有明确指定,ES6 类也默认在严格模式下执行。这就是为什么 this 将是 undefined 如果没有绑定到类。

【讨论】:

  • 在严格模式下,这将是未定义的。即使在非严格模式下,类也会像在严格模式下一样执行。这就是为什么它在反应类方法中打印 undefined 而不是 window 对象
  • 谢谢,这是我正在寻找的确切答案,因为组件在 DOM 中呈现,所以它们处于不同的执行上下文中。
【解决方案2】:

出于这个原因,您发布的 sn-ps 中未定义,它们未定义。

首先,你问为什么你需要让函数工作——因为你试图调用组件'this'来调用设置状态。因此,您只需从组件构造函数中绑定 this,这样当您调用该函数时,“this”就被定义并设置为组件“this”。

【讨论】:

  • 我认为您的回答基本上是正确的,但您可能需要重构您的发音。
猜你喜欢
  • 2018-12-26
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 2014-06-12
相关资源
最近更新 更多