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
. I could normally do this with references if I was in the render()
function, but I am in an event.
但是我必须调用一个Portal内的函数。如果我在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函数中为动态创建的组件调用组件函数?
1 个解决方案
#1
0
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>
);
}
#1
0
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>
);
}