【问题标题】:React Router: custom browser router getUserConfirmation dialogReact Router:自定义浏览器路由器 getUserConfirmation 对话框
【发布时间】:2019-02-15 17:01:25
【问题描述】:

我有自定义的BrowserRouter 组件,因为我需要从 React 组件中访问历史实例,所以我以这种方式创建它:

OwnBrowserRouter.js

import { BrowserRouter } from "react-router-dom"
import { createBrowserHistory } from "history"

export const history = createBrowserHistory()

export default class OwnBrowserRouter extends BrowserRouter {
  history = history
}

然后我在我的应用程序中使用这个OwnBrowserRouter 组件并通过自定义模式传递getUserConfirmation 组件:

App.js

<OwnBrowserRouter getUserConfirmation={getUserConfirmation}> ... </>

getUserConfirmation.js

const getUserConfirmation = (message, callback) => {
  const modal = document.createElement("div")
  document.body.appendChild(modal)

  const withCleanup = answer => {
    ReactDOM.unmountComponentAtNode(modal)
    document.body.removeChild(modal)
    callback(answer)
  }

  ReactDOM.render(
    <ConfirmModal
      open={true}
      type={MODAL.TYPE.CANCEL}
      handleClose={() => withCleanup(false)}
      handleConfirm={() => withCleanup(true)}
      title="Are you sure?"
      text={message}
    />,
    modal
  )
}

export default getUserConfirmation

然后我(当然)在某处渲染&lt;Prompt&gt; 组件...主要问题是它适用于从react-router-dom 导入的原点BrowserRouter 但每当我切换到OwnBrowserRouter 时,它开始显示丑陋浏览器对话框(不是我的自定义样式模式)。

【问题讨论】:

  • 无需创建自定义浏览器路由器,您可以使用 this.props.history 从 BrowserRouter 访问历史记录
  • @Nisfan 正如我所写,我需要访问反应组件之外的历史记录,而你没有道具。

标签: reactjs react-router react-router-dom


【解决方案1】:

对于任何有兴趣回答的人,getUserConfirmation实际上是一个历史API,所以解决方案是

export const history = createBrowserHistory({ getUserConfirmation })

【讨论】:

  • 这对于那些使用来自'react-router'的低级路由器的人来说很棒,它不接受getUserConfirmation作为道具。谢谢,@ketysek
猜你喜欢
  • 1970-01-01
  • 2016-06-09
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 2011-03-16
  • 1970-01-01
  • 2020-08-02
相关资源
最近更新 更多