ReactJS - 从map函数调用函数,函数未定义

时间:2016-01-08 13:39:01

标签: javascript reactjs

我正在尝试调用getElementByKey()函数来映射集合:

{this.state.sections.map(function(section) {
                return (<Tab key={section.value} title={section.label}>
                        {this.getElementByKey(section.name)}
                </Tab>);
            })}

以下是我试图调用的方法:

getElementByKey: function(name){

    switch(name) {
        case "EditStudentBasicDetails":
            return <EditStudentBasicDetails studentId={this.state.studentId} sectionData={this.state.studentData.activeData.basicDetails} />;
        case "EditStudentAgentsInfo":
            return <EditStudentAgentsInfo  studentId={this.state.studentId} sectionData={this.state.studentData.activeData.agentsInfo} />;
        case "EditStudentCaseNotes":
            return <EditStudentCaseNotes studentId={this.state.studentId} sectionData={this.state.studentData.activeData.caseNotes}/>;
        case "EditStudentRegistration":
            return <EditStudentRegistration studentId={this.state.studentId} sectionData={this.state.studentData.activeData.registration} />;
        case "EditStudentContactDetails":
            return <EditStudentContactDetails studentId={this.state.studentId} sectionData={his.state.studentData.activeData.contactDetails} />;
        case "EditStudentAttendance":
            return <EditStudentAttendance studentId={this.state.studentId} sectionData={this.state.studentData.activeData.attendance} />;
        case "EditStudentSENDetails":
            return <EditStudentSENDetails studentId={this.state.studentId} sectionData={this.state.studentData.activeData.SENDetails} />;
        case "EditStudentSENReviews":
            return <EditStudentSENReviews studentId={this.state.studentId} sectionData={this.state.studentData.activeData.SENReviews} />;

        default:{

        }
    }

},

我收到错误,this.getElementByKey不是函数,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

目前,this是映射函数,而不是您可能怀疑的组件。

.map()接受第二个参数,它将映射函数的上下文设置为传递的任何对象。

.map(function () {}, this);

或者您可以使用.bind()更改this的含义。

this.state.sections.map(function() {}.bind(this));