ReactJS - 在多个子类上传递方法时,TypeError未定义类

时间:2018-05-17 05:59:49

标签: javascript reactjs arrow-functions

我在MainDeck类上得到了错误Unable to read property moveToExtraDeck of undefined,尽管我在其构造函数中bind类方法。这是父MainDeck类:

//Omitted import statements ...

export default class MainDeck extends React.Component {
    constructor(props) {
        super(props);
        this.moveToExtraDeck = this.moveToExtraDeck.bind(this);
        this.state = ...
    }

    moveToExtraDeck() {
        alert('This card cannot reside in Extra Deck.');
    }

    render () {
        return (
            <div class="ui card">
                ....
                <div class="extra content">
                    <div class="ui stackable grid">
                    {
                        this.state.cards.map(function(card, i) {
                            return <Card card={ card } deck={ 'main' } moveToExtra={ this.moveToExtraDeck } />;
                        }, this) //Just bind the class here as suggested
                    }
                    </div>
                </div>
            </div>
        )
    }
}

这个班级CardMainDeck班级的孩子:

//Omitted import statements ...

export default class Card extends React.Component {
    constructor(props) {
        super(props);
        this.state = ...
    }

    render () {
        return (
            <div class="ui card">
                ....
                <div class="extra content">
                    <Button deck={ this.state.deck } onClick={ this.props.moveToExtra } />
                </div>
            </div>
        )
    }
}

最后,Button类是Card class:

的子级
//Omitted import statements ...

export default class Button extends React.Component {
    render () {
        return (
            <div class="ui simple dropdown">
                <button
                    class={ this.props.deck === 'extra' ? 'disabled item' : 'item' }
                    onClick={ this.props.onClick }>Extra Deck</button>
            </div>
        )
    }
}

如果我的代码是一个反模式,我感到很困惑,当我将方法传递给多个生成未定义父类的子类时,我感到很困惑。

更新:我已根据建议编辑了代码,并将MainDeck类绑定到map。它可以显示页面。单击按钮但未显示警报时,不会抛出错误。我不知道为什么。

0 个答案:

没有答案