不能使用React从子组件调用父组件中的函数

时间:2016-10-13 03:08:59

标签: javascript reactjs

我有2个文件:

grid-body.jsx(GridBody)和grid-row.jsx(GridRow)

在GridBody中,我声明了一个函数showAlert,我传递给每个GridRow:

var GridBody = React.createClass({
    showAlert: function(msg) {
        alert(msg);
    },

    render: function() {
        var rows = this.props.rows.map(function(li) {
            return (
                <GridRow showAlert={this.showAlert} />
            );
        });

        return (
            <div>
                {rows}
            </div>
        );
    }
});

在GridRow中:

var GridRow = React.createClass({
    toggle: function() {
        this.props.showAlert('HEY');        // -----> ERROR - not a function
    },

    render: function() {
        <div>
            <a href="#" onClick={this.toggle} />
        </div>
    }
});

我试图从父母那里调用showAlert,根据我见过的例子,这是怎么做的,但是我无法让它发挥作用。

2 个答案:

答案 0 :(得分:2)

您在this内使用了GridView.render的错误值。将其明确传递给Array.map()(请参阅docs了解如何执行此操作)或将this分配给render()顶部的某个新变量,并将其引用。

Here是一个非常非常好的评论,为什么会发生这种情况,以及其他一些替代解决方法,如果以上两种方法都不适合你。

答案 1 :(得分:0)

在GridBody的render方法中传递给map的函数的上下文是window而不是组件。您可以绑定interatee以获得所需的行为:

render: function() {
    var rows = this.props.rows.map(function(li) {
        return (
            <GridRow showAlert={this.showAlert} />
        );
    }.bind(this));

    return (
        <div>
            {rows}
        </div>
    );
}
相关问题