通过道具将功能传递给组件 - REACT

时间:2016-02-18 19:24:40

标签: reactjs

我试图通过' handleItemClick'功能来自' Dropdown'组件,直到他们'团队'但是,我无法通过“List'零件。奇怪的是,当我将道具记录在' List'它说' itemClick'是在' this.props'对象然而当我把它设置为团队'它说的组件"无法读取属性' itemClick'未定义"。

非常感谢任何帮助。

下拉组件:

var Dropdown = React.createClass({
    getInitialState: function(){
        return {
            display: false
        };  
    },
    handleClick: function(e){
        this.setState({display: !this.state.display})
    },
    handleItemClick: function(e){
        console.log("Something");
    },
    render: function(){
        return (
            <div className="dropdown">
                <Button whenClicked={this.handleClick} className="btn-default" title={this.props.data.title} number={this.props.data.teams.length} />
                <List teams={this.props.data.teams} display={this.state.display} itemClick={this.handleItemClick}/>
            </div>
        );   
    }
});

列表组件:

var List = React.createClass({
    render: function(){
        console.log(this.props)
        var teams = this.props.teams.map(function(team){
            return <Team key={team} team={team} teamChoice={this.props.itemClick}  />
        });

        var displayStyle = {
            display: this.props.display ? 'block' : 'none'
        };

        return (
            <ul style={displayStyle} className="dropdown-menu">
                {teams}
            </ul>
        );
    }
});

2 个答案:

答案 0 :(得分:6)

Kristofen44很接近:

Array.prototype.map()在其回调中丢失了来自父作用域的this。但该函数包含一个用于访问其中this的变量输入:

var teams = this.props.teams.map(function(team){
    return <Team key={team} team={team} teamChoice={this.props.itemClick}  />
}, this);

答案 1 :(得分:1)

我不确定,但我认为当您将团队映射到生成节点时,错误存在于List Component的渲染功能中。地图回调函数会丢失上下文&#39; this&#39;。我认为你必须将回调函数绑定到&#39;这个&#39;明确。 像这样:

var teams = this.props.teams.map(function(team){
    return <Team key={team} team={team} teamChoice={this.props.itemClick}  />
}.bind(this)); // <------
顺便说一下,作为一个很新的反应,我不知道将一个整个对象传递给属性&#39; key&#39;是否是一个好习惯。你的团队组件......我想知道如果传递一个id或类似的东西并不是更好..

希望有所帮助

相关问题