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

Can't call function in parent component from child component using React

本文关键字:组件 调用 函数 React 不能      更新时间:2023-09-26

我有两个文件:

grid-body。jsx (GridBody)和gridrow。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>
        );
    }
});

var GridRow = React.createClass({
    toggle: function() {
        this.props.showAlert('HEY');        // -----> ERROR - not a function
    },
    render: function() {
        <div>
            <a href="#" onClick={this.toggle} />
        </div>
    }
});

我正在尝试从parent调用showAlert,根据我所看到的例子,这就是如何做到这一点,但我不能使它工作

您在GridView.render中使用了错误的this值。要么将它显式地传递给Array.map()(请参阅文档了解如何做到这一点),要么将this分配给render()最顶部的一些新变量并引用它。

这里有一个非常非常好的SO评论,解释了为什么会发生这种情况,以及如果以上两种方法都不适合你的话,还有一些其他的解决方法。

在GridBody的渲染方法中传递给map的函数的上下文是窗口而不是组件。您可以绑定交互对象以获得您想要的行为:

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