【问题标题】:React js: Why I'm unable to create closure?React js:为什么我无法创建闭包?
【发布时间】:2016-05-31 20:33:41
【问题描述】:

我有 isLeap 作为检查当前年份是否为闰年的道具和另一个道具 currentMonth 这是当前月份的计数。 (例如 1 代表 2 月)

当我尝试在函数或闭包中创建函数时,控制台抛出 "Unexpected token" 错误,如下所示

  70 |  },
  71 |  daysInMonth : function(d){
> 72 |      var leapCase = function(this.props.isLeap){
     |                           ^
  73 |      }
  74 |  },
  75 |  render : function(){

在渲染函数中,我通过组件的属性调用上述函数:

<Week key={i} dayCount = {this.daysInMonth(this.props.currentMonth)} />

【问题讨论】:

  • Unexpected token this ?
  • with leapcase 我正在尝试检查二月是否属于闰年。如果是,则返回 29,否则返回 28。

标签: javascript reactjs closures


【解决方案1】:

您尝试使用参数this 启动函数,该参数用于确定函数的调用方式。如果你想在闭包中访问 this.props,试试这个。

  70 |  },
  71 |  daysInMonth : function(){
            var props = this.props
  72 |      var leapCase = function(){
     |         console.log(props.isLeap)
  73 |      }
  74 |  },
  75 |  render : function(){

在渲染函数中,像这样调用它

<Week key={i} dayCount = {this.daysInMonth.bind(this)} />

【讨论】:

  • @Haketo 哎呀,我忘了
【解决方案2】:

要定义一个闭包,你需要像这样包装函数

var leapCase = (function(props){

    return function(){
        if (props.isLeap){
            ...
        }
    };    

})(this.props)

【讨论】:

  • 谢谢。很有用!
【解决方案3】:

你有语法错误,你不能使用.thisin name of function argument

var leapCase = function(isLeap) {
  // ... 
};

leapCase(this.props.isLeap)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多