【问题标题】:How to add a onclick event in ag-grid cell renderer reactjs and access the class function如何在 ag-grid 单元格渲染器 reactjs 中添加 onclick 事件并访问类函数
【发布时间】:2019-03-05 22:24:22
【问题描述】:

我想在时间列定义时为 reactjs 中的 ag-grid 表列添加一个按钮。 onclick 我需要调用一个类函数。 我想创建 onclick 事件并将参数值传递给函数并从那里进行 api 调用。

columnDefs = [{
    ..... {
      headerName: "View",
      field: "id",
      sortable: false,
      filter: false,
      colId: "view",
      cellRendererFramework: function(params) {
        return <Button onclick = {
          this.handleClick
        } > Test < /Button>
      },

    },
    ......
  ];
}
handleClick() {
  console.log("some API call and state change");
}



render() {

    return ( <
      div >
      <
      div id = "myGrid"
      style = {
        {
          height: "100%",
          width: "100%"
        }
      }
      className = "ag-theme-material" >
      <
      AgGridReact enableSorting = {
        true
      }
      groupSelectsChildren = {
        true
      }
      rowData = {
        this.state.organization
      }
      columnDefs = {
        this.columnDefs
      }

      onGridReady = {
        this.onGridReady
      } >

      <
      /AgGridReact>

      <
      /div>


    }
    export default OrganizationList;

【问题讨论】:

  • 你真的认为问这样的问题会帮助我们理解实际问题吗?至少分享你尝试过的代码
  • 这对我有用cellRendererFramework: (props) =&gt; { return ( &lt;button onClick{this.handleClick.bind(this)&gt;Click&lt;/button&gt; } ); }

标签: reactjs ag-grid-react


【解决方案1】:

不要在列定义中使用 cellRenderer,而是使用 cellRendererFramework,这样 agGridReact 就会知道您正在返回 jsx 元素。

例如:

colDefs = [{ ...{
headerName: "View",
field: "id",
colId: "view",
cellRendererFramework: function(params) {
  return <button onClick={ this.handleClick }> Test </button>
},
  },
  ....
}]

也不要忘记将单元格渲染器函数绑定到您的组件类构造函数,否则您将无法访问this

【讨论】:

  • TypeError: 无法读取未定义的属性 'handleClick' 收到此错误。按照你说的做了更改,如果我错了,请告诉我。 const columnDefs = [{ { .... { headerName: "View", field: "id", colId: "view", cellRendererFramework: function(params) { return &lt;Button onclick={this.handleClick}&gt; View &lt;/Button&gt; } ..... ]; class Test extends React.Component { constructor(props) { super(props) this.handleClick = this.handleClick.bind(this); }
  • handleclick 未绑定到您的组件类。在this.statethis.handleClick = this.handleClick.bind(this);之前的构造函数中添加这一行
  • 您已经在组件类之外定义了列定义,handleClick 在测试类中。将 columnDefs 放入 state 并在渲染时将其传递给 agGridReact
  • 1.我在类外定义 columnDefs。 2. 我没有在构造函数中定义状态。 3. 我在super(props) 之后定义this.handleClick = this.handleClick.bind(this);
  • 您可以在构造函数this.columnDefs=columnDefs 中执行此操作,然后在渲染agGridReact columnDefs={this.columnDefs} 时执行此操作
猜你喜欢
  • 2017-09-10
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 2018-02-13
  • 2021-05-12
  • 2017-06-11
  • 2018-05-23
  • 2018-10-13
相关资源
最近更新 更多