反应。从外部变量调用函数

ReactJS. calling a function from an outside variable

我是 ReactJS 的新手,正在尝试制作一个小型 Web 应用程序。 我有一个要放在侧边栏中的项目列表,我希望每个项目在单击时返回侧边栏的状态(以便我可以相应地设置活动 link 的样式)。

import React, {Component} from 'react';
import SideBarItem from "./SideBarItem";

const items = {
    'DASHBOARD' : 'home',
    'Utenti': 'user',
    'Corsi' : 'education',
    'Logistica' : 'check',
    'Comunicazioni': 'bullhorn'
};

const listItems = Object.entries(items).map(([key,value])=>{
    return <SideBarItem 
                onClick={this.changeState(key)} active={this.state.active == key ? 'active' : ''} 
                title={key} 
                glyph={'glyphicon glyphicon-' + value.toString()}/>
});

class SideBar extends Component {
    constructor(props) {
        super(props);
        this.state = {active: 'DASHBOARD'};
}

    changeState (row) {
        this.setState({
            active: row
        });
    }

    render() {
        return (
            <div id = "sidebar" className="col-sm-3 col-md-2 sidebar paper-depth-1">
                <ul className = 'nav nav-sidebar'>
                    {listItems}
                </ul>
            </div>
        );
    }
}


export default SideBar;

但是此代码返回以下错误:

TypeError: _this.changeState is not a function

我知道从外部变量调用组件函数有问题,但我不知道如何以任何其他方式使它工作。

如果您在 render() 中创建项目列表,this 范围将是组件实例,正如您所需要的那样。

class SideBar extends Component {
    constructor(props) {
        super(props);
        this.state = {active: 'DASHBOARD'};
    }

    changeState(row) {
        this.setState({
            active: row
        });
    }

    render() {
        return (
            <div id="sidebar" className="col-sm-3 col-md-2 sidebar paper-depth-1">
                <ul className="nav nav-sidebar">
                    {Object.entries(items).map(([key,value]) =>
                        <SideBarItem 
                            onClick={() => this.changeState(key)}
                            active={this.state.active == key ? 'active' : ''} 
                            title={key} 
                            glyph={'glyphicon glyphicon-' + value.toString()}
                        />
                    )}
                </ul>
            </div>
        );
    }
}