【问题标题】:How to call function within component property?如何在组件属性中调用函数?
【发布时间】:2019-12-12 09:43:33
【问题描述】:

在这种情况下,当我尝试在组件的属性中调用方法或设置状态时,Sortablejs 方法返回未定义的错误。

<Sortable options={{ 
animation: 150,
                onAdd: function(/**Event*/ evt) {
                  this.testFunction();//this doesnt seem to work??
                },
                group: {
                  name: "clone2",
                  pull: true,
                  put: true
                }
              }}
              className="block-list A"          
              tag="ul"
            >
              {cloneControlledTarget}
            </Sortable>
              <Sortable
                options={{
                  animation: 150,
                  sort: false,
                  group: {
                    name: "clone2",
                    pull: "clone",
                    put: false
                  }
                }}
                className="block-list"
                tag="ul"
              >
                {cloneControlledSource}
              </Sortable>

【问题讨论】:

标签: reactjs sortablejs


【解决方案1】:

我认为问题出在以下代码中。使用箭头函数代替传统的匿名函数

onAdd: function(/**Event*/ evt) {
  this.testFunction();//this doesnt seem to work??
}

这样使用

onAdd: (/**Event*/ evt) => {
  this.testFunction();
}

如果 testFunction 在您的组件中可用,这应该可以工作。

【讨论】:

    【解决方案2】:

    你正在传递一个对象

                  { 
                    animation: 150,
                    onAdd: function(/**Event*/ evt) {
                      this.testFunction();
                    },
                    group: {
                      name: "clone2",
                      pull: true,
                      put: true
                    }
                  }
    

    到选项属性。所以在函数onAdd里面,“this”的值是指对象的属性。由于对象内部没有testFunction,所以会抛出引用错误。请改用箭头功能。

    onAdd: () => { this.testFunction() }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 2019-09-02
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多