簡體   English   中英

通過props將功能傳遞給組件-REACT

[英]Passing a function down to a component through props - REACT

我試圖將“ Dropdown”組件中的“ handleItemClick”功能傳遞給他們的“ Team”組件,但是,我無法通過“ 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>
        );
    }
});

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);

我不確定,但是當您映射團隊以生成節點時,我認為錯誤出在List Component的render函數中。 地圖回調函數將丟失上下文“ this”。 我認為您必須將回調函數明確綁定到“ this”。 像這樣:

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

順便說一句,由於反應很新,我不知道將整個對象傳遞給Team組件的屬性“鍵”是否是一種好習慣……我想知道傳遞一個ID或類似的東西是否更好? ..

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM