【问题标题】:Do closures work the same way on class methods?闭包在类方法上的工作方式是否相同?
【发布时间】:2019-05-07 11:34:22
【问题描述】:

我刚刚开始学习 React.js(和 Javascript),我有一个非常基本的问题要问你们。

这是一个小组件的工作示例,它创建了 3 个按钮,每次单击按钮时,其值都会递增。

class Button extends React.Component {

handleClick = () => {
    this.props.onClickFunction(this.props.incrementValue);
}
render(){
    return(
    <button onClick={this.handleClick}>
        {this.props.incrementValue}
    </button>
    );
    }
}

const Result = (props) => {
    return(
    <div>{props.counter}</div>
  );
};

class App extends React.Component {
    state = {counter: 0};
  incrementCounter = (incrementValue) => {
    this.setState((prevState) => ({
            counter: prevState.counter + incrementValue
    }));
    };

    render() {
    return (
        <div>
        <Button incrementValue={2} onClickFunction={this.incrementCounter}/>
      <Button incrementValue={10} onClickFunction={this.incrementCounter}/>
      <Button incrementValue={99} onClickFunction={this.incrementCounter}/>
      <Result counter={this.state.counter}/>
    </div>
    );  
  }
}

ReactDOM.render(<App />, mountNode);

在体验代码时,我尝试更改handleClick函数。

class Button extends React.Component {

handleClick(){
    this.props.onClickFunction(this.props.incrementValue);
}
render(){
    return(
    <button onClick={this.handleClick}>
        {this.props.incrementValue}
    </button>
    );
    }
}

const Result = (props) => {
    return(
    <div>{props.counter}</div>
  );
};

class App extends React.Component {
    state = {counter: 0};
  incrementCounter = (incrementValue) => {
    this.setState((prevState) => ({
            counter: prevState.counter + incrementValue
    }));
    };

    render() {
    return (
        <div>
        <Button incrementValue={2} onClickFunction={this.incrementCounter}/>
      <Button incrementValue={10} onClickFunction={this.incrementCounter}/>
      <Button incrementValue={99} onClickFunction={this.incrementCounter}/>
      <Result counter={this.state.counter}/>
    </div>
    );  
  }
}

ReactDOM.render(<App />, mountNode);

我现在得到:Uncaught TypeError: Cannot read property 'props' of undefined 在句柄点击处(评估在

据我了解,匿名函数 handleClick = () =>... 由于闭包,可以从父级访问道具,但是当我将其替换为类时,为什么魔术会停止方法?

【问题讨论】:

标签: javascript reactjs closures


【解决方案1】:

您的问题似乎不是关于闭包,而是关于 this 在 JS 中的工作方式。在您的工作示例中

handleClick = () => {
    this.props.onClickFunction(this.props.incrementValue);
}

您有一个箭头函数,因此您的this 始终指向您的实例,这就是您可以访问this.props 的原因。

在你的非工作示例中

handleClick(){
    this.props.onClickFunction(this.props.incrementValue);
}

您不再有箭头函数,所以现在this 在调用函数时不再引用您的实例。这就是您无法访问this.props 的原因。

您可以像在工作案例中那样使用箭头函数来解决此问题,或者您可以将您的函数绑定到当前实例,以确保 this 始终指向您的实例。

【讨论】:

    猜你喜欢
    • 2013-10-25
    • 2015-08-12
    • 1970-01-01
    • 2011-10-09
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    相关资源
    最近更新 更多