javascript - 如何在 React 组件的返回函数中使用 IIFE?

标签 javascript reactjs

当用户单击按钮时,我会弹出一个模态页面,它运行良好:

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(一个立即调用的函数表达式)以便在用户打开页面时立即打开模式吗?

  • 我的方法是将 bool 值设置为 true。如果该值设置为 true,则打开模态

用于模态的库: https://github.com/marcio/react-skylight

最佳答案

我认为您正在寻找的是 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 .

关于javascript - 如何在 React 组件的返回函数中使用 IIFE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41412981/

相关文章:

javascript - 以下表达式如何计算为 "10"

javascript - Reactjs .NET 中的函数永远无法实现 - 如何在渲染中调用简单的箭头函数?

javascript - 无法在 Next 中传递 props

php - 是否可以动态更改网页的 URL?

javascript - 如何从下拉列表中删除除从另一个下拉列表中选择的值之外的所有值

javascript - 将 Redux 映射状态 react 到 Prop 不起作用

reactjs - 两个 svgo-loader 冲突

javascript - 渲染方法在内部映射值时中断

javascript - React Redux 未在 mapStateToProps 中获取状态

javascript - 在js数组中查找下一个和上一个键