如何在 React 组件的 return 函数中使用 IIFE?
How can I use an IIFE in the return function of a react component?
当用户单击按钮时,我会弹出一个模态页面,它运行良好:
render() {
return (
<div>
<section>
<button onClick={() => this.refs.simpleDialog.show()}>Open Modal</button>
</section>
<SkyLight hideOnOverlayClicked ref="simpleDialog" title="Test Modal">
Text that appears inside the modal page
<Button onClick={() => this.refs.simpleDialog.hide()} >Got It</Button>
</SkyLight>
</div>
)}
但我的目标是在用户第一次打开页面时自动打开模式。
我不想通过点击按钮打开模式页面
问题:
我可以使用 IIFE(立即调用的函数表达式)以便在用户打开页面时立即打开模式吗?
我的方法是将布尔值设置为真。如果该值设置为 true
然后打开模态
要在组件安装时打开模型,只需将 isVisible 设置为 true
<SkyLight isVisible={true} ref="simpleDialog" title="Test Modal">
我认为您正在寻找的是 componentDidMount() 生命周期方法:
componentDidMount() {
this.refs.simpleDialog.show();
}
来自React docs:
componentDidMount()
is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
随时查看其他 component lifecycle methods。
当用户单击按钮时,我会弹出一个模态页面,它运行良好:
render() {
return (
<div>
<section>
<button onClick={() => this.refs.simpleDialog.show()}>Open Modal</button>
</section>
<SkyLight hideOnOverlayClicked ref="simpleDialog" title="Test Modal">
Text that appears inside the modal page
<Button onClick={() => this.refs.simpleDialog.hide()} >Got It</Button>
</SkyLight>
</div>
)}
但我的目标是在用户第一次打开页面时自动打开模式。
我不想通过点击按钮打开模式页面
问题:
我可以使用 IIFE(立即调用的函数表达式)以便在用户打开页面时立即打开模式吗?
我的方法是将布尔值设置为真。如果该值设置为 true
然后打开模态
要在组件安装时打开模型,只需将 isVisible 设置为 true
<SkyLight isVisible={true} ref="simpleDialog" title="Test Modal">
我认为您正在寻找的是 componentDidMount() 生命周期方法:
componentDidMount() {
this.refs.simpleDialog.show();
}
来自React docs:
componentDidMount()
is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
随时查看其他 component lifecycle methods。