简体   繁体   English

如何从javascript函数内部调用React组件函数?

[英]How to call a React component function from inside a javascript function?

I am in an event function and I would like to create a new alert popup (I am using the react-portal library): 我在一个事件函数中,我想创建一个新的警报弹出窗口(我正在使用react-portal库):

onNewAlert: function(username) {

    var divModal = (
        <Portal ref={'Portal'+username}>
                <div id={'div'+username}>
                    <br /><br/ >Alert for {username}
                </div>
        </Portal>);
    ...
}

But then I would have to call a function that is inside a Portal . 但是然后我将不得不调用Portal内的函数。 I could normally do this with references if I was in the render() function, but I am in an event. 如果我在render()函数中,我通常可以使用引用来执行此操作,但是我处于事件中。

    this.refs['Portal'+username].openPortal(); // openPortal is a function of the Portal component

Is there a way to call a component function for a component created on the fly in a javascript function? 有没有办法为javascript函数中动态创建的组件调用组件函数?

Even if you could call portal.openPortal() it wouldn't do anything since the component created in the event handler wouldn't be attached to the DOM. 即使您可以调用portal.openPortal()它也不会做任何事情,因为在事件处理程序中创建的组件不会附加到DOM。

Instead of trying to render the Portal in the event handler function, the event handler should change the component state which will trigger render() . 事件处理程序应该更改将触发render()的组件状态,而不是尝试在事件处理函数中呈现Portal。

onNewAlert: function(username) {
    this.setState({ showAlert: true });
}

The render() function would then use the state variable for the Portal component's isOpened property: 然后, render()函数将状态变量用于Portal组件的isOpened属性:

render: function () {
    return (
        <div>
            ...
            <Portal isOpened={this.state.showAlert}>
                ...
            </Portal>
        </div>
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM