我正在使用react-router-dom
,我希望能在点击浏览器返回按钮时关闭模态框。
此外,在我的场景中,模态框组件不是Switch
的一部分。那么我该如何关闭模态框呢?
谢谢提前。:)
我正在使用react-router-dom
,我希望能在点击浏览器返回按钮时关闭模态框。
此外,在我的场景中,模态框组件不是Switch
的一部分。那么我该如何关闭模态框呢?
谢谢提前。:)
componentDidUpdate() {
window.onpopstate = e => {
}
}
然后,根据您的模态框(Bootstrap或其他)的不同,您可以调用.hide()
或.close()
。
我已经制作了一个简单的钩子,叫做useAppendLocationState
,它可以完成所有工作:
function SomeComponent() {
const [showModal , appendShowModal ] = useAppendLocationState('showModal');
return (
<div>
<div>...some view...</div>
<button onClick={() => appendOpenModal(true)}>open modal</button>
{showModal && <SomeModal closeHandler={() => window.history.back()} />}
</div>
)
}
useAppendLocationState
返回一个数组,就像 useState
一样,第一个条目是来自浏览器位置状态的状态属性值,第二个条目是将新项目推送到浏览器历史记录的方法,并将新状态属性附加到当前位置状态。
这是我们的useAppendLocationState
定义:
import { useHistory } from 'react-router';
export function useAppendLocationState(key) {
if (!key) throw new Error("key cannot be null or empty value")
const history = useHistory()
const currentLocationState = history.location.state;
const appendStateItemValue = (value) => {
const newLocationState = { ...currentLocationState }
newLocationState[key] = value;
history.push(history.location.pathname, newLocationState)
}
const stateItemValue = history.location.state && history.location.state[key]
return [stateItemValue, appendStateItemValue]
}
export default useAppendLocationState