In the following example I'm trying to better understand the bind method.
(在下面的示例中,我试图更好地理解bind方法。)
Specifically, what do the two instances of 'this' refer to and why do we need the second one?(具体来说,“ this”的两个实例指的是什么,为什么我们需要第二个实例?)
Also, why don't I need to include 'this' in the callback:(另外,为什么我不需要在回调中包含“ this”:)
UPDATE:
(更新:)
I understand now that they both refer to FontChooser but why do we want to bind FontChooser.checkbox to FontChooser?
(现在我知道它们都引用了FontChooser,但是为什么我们要将FontChooser.checkbox绑定到FontChooser?)
Isn't that redundant?(那不是多余的吗?)
or in other words if 'this' refers to the class why do we need to bind a class callback (this.checkbox) to the class (this.checkbox.bind(this))?(或者换句话说,如果“ this”是指类,为什么我们需要将类回调(this.checkbox)绑定到类(this.checkbox.bind(this))?)
It's almost like we are binding a specific instance back to the class callback but (a) where are we creating the specific instance and (b) shouldn't the specific instance already have the class callback
(几乎就像我们将特定实例绑定回类回调一样,但是(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>
);
}
}
ask by DCR translate from so