在reactive bind中,“这个”指的是什么?

问题描述 投票:-1回答:1

在下面的示例中,我试图更好地理解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>
    );
  }
}
javascript reactjs bind
1个回答
0
投票

在javascript中,根据所执行的上下文,this关键字指向不同的对象。在JSX“模板”中使用函数时,该函数不在类中执行,而在其他上下文中执行反应结果,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

© www.soinside.com 2019 - 2024. All rights reserved.