【问题标题】:Binding this on method receiving parameters在方法接收参数上绑定 this
【发布时间】:2018-08-16 16:39:16
【问题描述】:

我有一个事件处理程序,它调用一个粗箭头函数来运行一个方法。

import React, { Component } from 'react';

class App extends Component {
  sayHi = msg => {
    console.log(msg);
  };

  render() {
    return (
      <div>
        <button onClick={() => this.sayHi('Hi')}>Console Hi!</button>
      </div>
    );
  }
}

export default App;

我正在学习上下文和 bind(),我想将此示例转换为绑定 this。我的问题是当胖箭头函数执行方法时我传递的参数,也就是'Hi'

有没有办法保留这样的东西......

<button onClick={this.sayHi('Hi')}>Console Hi!</button>

我尝试了不同的方法,但没有好的结果。主要集中在

  constructor(props) {
    super(props);
    this.sayHi = this.sayHi.bind(this);
  }

  sayHi = () => {
    console.log(msg);
  };

是的...我不想将“嗨”移到方法或构造函数中。 我正在努力学习和理解。我将不胜感激任何形式的帮助或指导。

【问题讨论】:

标签: javascript reactjs this


【解决方案1】:

你在混合东西。您的情况有两种情况,您正在尝试同时使用它们。

绑定到这个

什么时候需要将函数绑定到this?如果你在回调中调用你的函数,比如你的按钮(当然是其中一种情况),并且你需要在这个函数中使用this,那么你需要绑定它。如果不使用this,也不需要绑定。

sayHi() {
    console.log("hi");
  };

  render() {
    return (
      <div>
        <button onClick={this.sayHi}>Console Hi!</button>
      </div>
    );
  }
}

这里,你不需要绑定它,你也可以使用带有引用的函数,因为没有参数。

constructor(props) {
    super(props);
    this.state = {
      name: "foo",
    }
    this.sayHi = this.sayHi.bind(this);
  }

  sayHi() {
    console.log(this.state.name);
  };

  render() {
    return (
      <div>
        <button onClick={this.sayHi}>Console Hi!</button>
      </div>
    );
  }
}

这里是在函数中使用this,所以需要在构造函数中绑定或者定义为箭头函数。

您的情况

现在,您的情况:您将函数定义为箭头,如果您将在那里使用this,则无需再绑定它。但是你没有使用它,那么不需要使用箭头功能。此外,您需要向它传递一个参数。所以,你需要找到一种方法来实现这一点。

第一种方法,对onClick使用箭头函数。因为如果你在这里不使用回调,你就不能使用click

sayHi(msg) {
    console.log(msg);
  };

  render() {
    return (
      <div>
        <button onClick={() => this.sayHi("hi")}>Console Hi!</button>
      </div>
    );
  }
}

如果您使用 this.sayHi("hi") 之类的方法,则在第一次渲染时调用此函数,而不是单击。

您也可以在此处使用.bind 作为第二种方法。

sayHi(msg) {
    console.log(msg);
  };

  render() {
    return (
      <div>
        <button onClick={this.sayHi.bind(null,"hi")}>Console Hi!</button>
      </div>
    );
  }
}

看,我们使用了 bind 但没有使用this,因为我们不需要它。我们没有在 sayHi 函数中使用 this

【讨论】:

  • 非常感谢。这真的有助于澄清我的精神混乱。
猜你喜欢
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
相关资源
最近更新 更多