如何在数据表的列中放置onClick?

Gau*_*mar 0 datatables reactjs

所以,一直在尝试在 reactjs 中使用数据表,我想在列中放置一个 onclick 但出现错误。

以下是我的代码:

const $ = require('jquery')
$.DataTable = require('datatables.net')
class Rmsdatatable extends Component {
    constructor(props) {
        super(props)
        this.handletableclick = this.handletableclick.bind(this)
    }
    handletableclick(event) {
        console.log(event)
    }
    componentDidUpdate() {
        console.log(this.props.data)
        this.$el = $(this.el)
        this.$el.DataTable(
            {
                data: this.props.data,
                scrollY: 520,
                paging: false,
                responsive: true,
                columns: [
                    {
                        data: "vfdSno",
                        render: function (data, type, row) {
                            return '<a onClick={' + this.handletableclick.bind(this, row) + '} >' + data + '</a>'
                        }
                    },
                    { data: "customerName" },
                    { data: "district" },
                    { data: "state" }
                ]
            }
        )
    }
    render() {
        return (
            <div style={{ 'padding': '10px' }} className="col-xs-10">
                <table id="example" className="display" width="100%" ref={el => this.el = el}>
                    <thead>
                        <tr>
                            <th>VFD/Controller No</th>
                            <th>Beneficiary</th>
                            <th>District</th>
                            <th>State</th>
                        </tr>
                    </thead></table>
            </div>

        )
    }
}
Run Code Online (Sandbox Code Playgroud)

作为参考,我正在使用此链接:

https://datatables.net/forums/discussion/38969/reload-refresh-table-after-event

错误是: TypeError: Cannot read property 'handletableclick' of undefined

感谢并感谢您的帮助。

小智 8

你可以试试这样吗:

 columnDefs: [
            {
                targets: 1,
                createdCell: (td, cellData, rowData, row, col) =>
                  ReactDOM.render(
                    <button
                      onClick={() => this.handletableclick(row) }>
                     data
                    </button>, td),
              } 
        ]
Run Code Online (Sandbox Code Playgroud)

  • 这个答案应该被提问者接受。因为我面临同样的问题,并且“createdCell”为我完成了工作。 (3认同)