在反应绑定中,“这个”指的是什么?

时间:2019-12-01 16:47:42

标签: javascript reactjs bind

在下面的示例中,我试图更好地理解bind方法。具体来说,“ this”的两个实例指的是什么,为什么我们需要第二个实例?另外,为什么我不需要在回调中包含“ this”:

更新:

我现在知道它们都引用FontChooser,但是为什么我们要将FontChooser.checkbox绑定到FontChooser?那不是多余的吗?或者换句话说,如果“ this”是指该类,为什么我们需要将一个类回调(this.checkbox)绑定到该类(this.checkbox.bind(this))?

几乎就像我们将特定实例绑定回类回调一样,但是(a)我们在哪里创建特定实例,(b)该特定实例不应该已经具有类回调

class FontChooser extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      hidden: true,
      checked: this.props.bold ? true : false
    };
  }

  displayButtons() {
    this.setState({
      hidden: !this.state.hidden
    });
  }

  checkbox() {
    //why not checkbox(this){
    this.setState({ checked: !this.state.checked });
  }

  render() {
    console.log(this.state);
    var weight = this.state.checked ? "bold" : "normal";

    return (
      <div>
        <input
          type="checkbox"
          id="boldCheckbox"
          hidden={this.state.hidden}
          checked={this.state.checked}
          onChange={this.checkbox.bind(this)}
        />
        <button id="decreaseButton" hidden={this.state.hidden}>
          {" "}
          -{" "}
        </button>
        <span id="fontSizeSpan" hidden={this.state.hidden}>
          {" "}
          {this.state.size}
        </span>
        <button id="increaseButton" hidden={this.state.hidden}>
          {" "}
          +{" "}
        </button>
        <span
          id="textSpan"
          style={{ fontWeight: weight, fontSize: this.state.size }}
          onClick={this.displayButtons.bind(this)}
        >
          {" "}
          {this.props.text}
        </span>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

在javascript中,this关键字根据执行它的上下文指向另一个对象。在JSX“模板”中使用函数时,该函数不在类中执行,而是在某些类中执行React中的其他上下文。结果,this所指的内容都被更改。

一种解决方法是使用bind()方法。此方法将替换其使用的所有功能,并将this关键字指向的所有内容替换为您提供的新位置。

在您的示例中,您正在使用this.displayButtons.bind(this)。在这里,this指的是此类(FontChooser),并且将确保this指向该类,而与执行上下文无关。

看看MDN文档,还有一些易于理解的示例。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind