React js:为什么我无法创建闭包

React js: Why I'm unable to create closure?

本文关键字:创建 闭包 js 为什么 React      更新时间:2023-09-26

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)} />

您尝试使用参数启动一个函数,该参数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)} />

要定义闭包,您需要像这样包装函数

var leapCase = (function(props){
    return function(){
        if (props.isLeap){
            ...
        }
    };    
})(this.props)

你有语法错误,你不能在函数参数的名称中使用.this

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