无法在反应中正确绑定此函数

时间:2016-05-12 18:23:38

标签: reactjs binding

我的handleTeamChange函数错误,并在renderTeamMethod运行时返回undefined。我尝试将变量团队传递给像“this.handleTeamChange.bind(this,team)”一样,但没有。我已经尝试了很多不同的方法来调用handleTeamChange方法,但到目前为止还没有定义。有什么想法吗?

import React, { Component } from 'react';
import UserDropdown from './user-dropdown';
import { getTeams } from 'api/index.js';

let teams = [];
let selectedTeamID = null;
let selectedTeamName = 'all_teams';
let teamId = '';

export default class TopNav extends Component {
   constructor(props, context) {
      super(props, context);
    // this.handleTeamChange = this.handleTeamChange.bind(this);
    this.state = {
        teams: [],
        team: {},
        selectedTeamID: null,
        selectedTeamName: 'All Teams',
        teamSelection: false
    };
}

handleClick() {
    this.setState({
        teamSelection: true
    });
}


componentWillMount() {
    getTeams().then((response) => {
        teams = response.data;
        this.setState({teams: teams});
    });
}

renderTeams() {
            return teams.map(function(team) {
                if (team.active === true) {
                    return (
                        <div
                          onClick={ () => { this.handleTeamChange(team) } }
                          className="team-filter-team"
                          key={team.id}
                          value={team.id} >{team.TeamName}
                        </div>
                    );
                }
            });
}

handleTeamChange(team) {
  console.log(team);
}

render () {
  return (
        <nav className="nav-wrapper">
            <img className="logo-medium nav-logo" src={"https://s3-us-west-2.amazonaws.com/mvtrak/MVTRAKbrandmark.png"} />
            <div onClick={ this.handleClick.bind(this) } className="team-selected"> { this.state.selectedTeamName } </div>
            <div className="team-filter-container">
                {this.renderTeams()}
            </div>
            <UserDropdown />
        </nav>

    );
}

}

1 个答案:

答案 0 :(得分:2)

您映射团队的函数体未绑定到组件的范围,因此thisundefined

teams.map(function (team) { ... })更改为例如胖箭teams.map((team) => ... )

return teams.filter(team => team.active).map((team) => (
  <div
    onClick={ () => { this.handleTeamChange(team) } }
    className="team-filter-team"
    key={team.id}
    value={team.id}
  >
    {team.TeamName}
  </div>
))