【问题标题】:ReactJs Passing parameters to parent without event handlerReactJs在没有事件处理程序的情况下将参数传递给父级
【发布时间】:2015-11-18 02:39:50
【问题描述】:

我需要在没有像 onClick 这样的事件处理程序的情况下将参数从子组件传递给父组件... 我的父组件有一个方法,子组件“A”每隔 x 秒必须将参数传递给父的方法。此方法更改父状态并将此值作为道具传递给另一个子组件“B”。 我该怎么做??

这是我的代码:

var Parent = React.createClass({
    getInitialState: function() {
        return {
            notification: [ {
                data: "-",
                message: "no notification to show",
                type: "-"
            } ]
        };
    },

    handleNotification: function(res) {
        var notification = this.state.notification;
        notification.push(res);
        this.setState({ notification: notification });
    },

    render: function() {
        return(
            <div>
                <Child callFunction={this.handleNotification} />
                <NotificationBox
                    notification={this.state.notification}
                    />
            </div>
        );
    }
});


var Child = React.createClass({
    displayName: "Child",

    handleReturnNotification: function(o) {
        this.props.callFunction.bind(o);
    },

    render: function() {
        var msg = "message:" ;
        var o = {
            data: "-",
            message: msg,
            type: "Alert"
        };
        this.handleReturnNotification.bind(this, o);

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

【问题讨论】:

  • 你有代码吗?
  • 我可以建议将像“onMount”这样的函数道具传递给孩子,然后让它在其componentDidMount中调用该函数(如果存在)。这比在实际渲染线程中执行回调要好得多。
  • 另外,如果逻辑就像您在代码中显示的那样,这严重破坏了 react 自上而下的方法。最好在父级中生成您的“o”对象,或者在子级上创建一个静态函数,您可以根据需要直接在父级和子级上调用该函数。

标签: javascript reactjs


【解决方案1】:

将父方法作为道具传递。在孩子A做this.props.parentMethod(parameter);

【讨论】:

    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2021-05-30
    • 2011-05-02
    相关资源
    最近更新 更多