ReactJS切换排序图标 - this.setState不是函数

时间:2016-01-12 12:15:44

标签: javascript reactjs

点击时,我试图切换每个表格标题的排序图标:

render我有:

 function bindContextOnClick(columnName){
        return function(){
            if(columnName === sortColumn) {
                sortOrder = (sortOrder === 'asc') ? 'desc' : 'asc';
                IconSort = (sortOrder === 'asc') ? 'top' : 'bottom';
            } else {
                sortOrder = 'asc';
                IconSort = 'top';
            }
            console.log(this);
            IconName = IconType + "-" + IconSort;

            this.setState({
                Icon: IconName
            }).bind(this);

            onToggleOrder(columnName, sortOrder);
        }
    }

然后,当我循环浏览我的json以生成我正在做的标题时:

     {this.props.rowScheme[i].title} <Glyphicon glyph={this.state.Icon} />

但我得到 this.setState不是函数

有人可以帮忙吗?

编辑,完整渲染:

getInitialState: function(){
    return {
        Icon: 'triangle-top'
    }
},

render: function() {
    var headerColumns = [];
    var IconType = 'triangle';
    var IconSort = 'top';
    var IconName = 'triangle-top';
    var onToggleOrder = this.props.onToggleOrder;
    var sortColumn = this.props.sortColumn;
    var sortOrder = this.props.sortOrder;

    function bindContextOnClick(columnName){
        return function(){
            if(columnName === sortColumn) {
                sortOrder = (sortOrder === 'asc') ? 'desc' : 'asc';
                IconSort = (sortOrder === 'asc') ? 'bottom' : 'top';
            } else {
                sortOrder = 'asc';
                IconSort = 'top';
            }
            IconName = IconType + "-" + IconSort;

            onToggleOrder(columnName, sortOrder);

            this.setState({
                Icon: IconName
            });
        }
    }

    for (var i = 0; i < this.props.rowScheme.length; i = i + 1) {
        // by default all visible columns are sortable, unless it has 'sortable'=false option
        if(_.has(this.props.rowScheme[i],"sortable") && !this.props.rowScheme[i].sortable) {
            headerColumns.push(<th key={_.uniqueId('edit_student_tbl_th_')}>{this.props.rowScheme[i].title}</th>);
        } else {

            headerColumns.push(
                <th key={_.uniqueId('edit_student_tbl_th_')}
                    onClick={bindContextOnClick(this.props.rowScheme[i].column).bind(this)}>
                    <span className="sortableColumn">
                        {this.props.rowScheme[i].title} <Glyphicon glyph={this.state.Icon} />
                    </span>
                </th>
            );
        }
    }

    return (
        <thead>
            <tr>
                {headerColumns}
                <th className={this.props.rowActionColumnClass}> </th>
            </tr>
        </thead>
    );
}
});

1 个答案:

答案 0 :(得分:1)

您需要将此上下文与函数绑定在一起。例如:onClick={this.bindContextOnClick(columnName)}

但需要这样:onClick={this.bindContextOnClick.bind(this, columnName)}