【问题标题】:DataTables - Calling functions in 'columnDefs' in reactDataTables - 在反应中调用“columnDefs”中的函数
【发布时间】:2022-02-24 21:00:42
【问题描述】:

所以当我在 react 中创建 DataTable 时,使用 columnDefs 属性定义某个列。

"columnDefs": [
            {
              "targets": 7,
              "data": "data",
              "render": function ( data, type, full, meta ) {
                return "<button onclick='test()'>view</button>"
              }
            }
          ]

但正如预期的那样,它找不到test() 函数。反正有没有做这种 jsx 风格的东西?还是我只需要在 onclick 中创建函数?

【问题讨论】:

    标签: javascript reactjs datatables


    【解决方案1】:

    你可以这样试试:

    $('#your_table').DataTable({
    
    . . . 
    
    "columnDefs": [{
                    "targets": 7,
                    "data": "data",
                    "render": function ( data, type, full, meta ) {
                                return "<button class='view_btn' data-id='"+data+"'>view</button>"
                              }
                  }]
    

    然后在外面创建测试函数:

    $('#your_table').on('click', '.view_btn', function(){
      var id = $(this).data('id');
      test(id); // your function
    });
    

    【讨论】:

    • 我或多或少在寻找一种以反应方式进行的方法,例如onclick={this.test}。如果不可能,那么带有解释的“不可能”答案就可以了。这是解决它的一种方法。
    【解决方案2】:

    在这种情况下您不能使用渲染,因为该函数将被直接调用。您可以在columnDefs 中使用箭头函数和createdCell insetead。 例如你在一个组件中有一个函数:

     this.test= this.test.bind(this);
    

    通过以下方式在columnDefs 中调用该函数:

    "columnDefs": [{
      "targets": 0,
      "data": "data",
      "createdCell": (td, cellData, rowData, row, col) => {
        $(td).click(e => {
          this.test();
        })
      }
    }]
    

    查看上面的链接了解更多信息。

    【讨论】:

    • 你可能是对的,虽然我无法再访问代码,所以我无法真正将其标记为答案:(
    • 旧答案,但它有效。易于定制。 ty
    【解决方案3】:

    可以使用箭头函数和this对象

    "columnDefs": [
                {
                  "targets": 7,
                  "data": "data",
                  "render": ( data, type, full, meta ) => {
                    return "<button onclick='this.test()'>view</button>"
                  }
                }
              ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      相关资源
      最近更新 更多