Dyl*_*ton 2 reactjs next.js react-hooks
我有一个被触发的模态,但不同组件之间有许多不同的按钮。例如,我已经能够通过在布局中传递变量来使其在页面上工作
const index = () => {
const [show, setShow] = useState(false)
const handleShow = () => { setShow(true) }
const handleClose = () => { setShow(false) }
<Layout pageTitle={pageTitle} metaUrl={metaUrl} show={show} onHide={handleHide}>
...
</Layout>
}
Run Code Online (Sandbox Code Playgroud)
并使用这些变量从布局传递到模态组件,从而触发模态。但它只适用于页面,因为我可以在布局中传递它们,但是我在导航栏和页脚中有按钮,这些按钮被导入到布局中而不是使用布局,所以我不确定如何实际将变量传递到模态那些。
任何帮助都会很棒!
对于这种情况,我认为完美的解决方案是使用 React Context,您可以将其分离在自己的钩子中,然后在应用程序需要时使用此钩子。首先,您需要创建上下文
const ModalContext = React.createContext()
// give it a display name so it would be easier to debug
ModalContext.dispalyName = 'ModalContext'
Run Code Online (Sandbox Code Playgroud)
那么您需要为此上下文创建 Provider 并将其放在应用程序树中更高的位置,因为您只能在其 Provider 下使用此上下文,因为您使用的是 Next.js 我建议在 _app.js 中或在您的应用程序周围执行此操作主要应用程序组件。
const ModalContextProvider = ({children}) => {
const [isOpend, setIsOpend] = React.useState(false);
// handle any additional data needed with useState/useReducer
const [title, setTitle] = React.useState('default title');
const value = {setIsOpened, setTitle};
return <ModalContext.Provider value={value}>
<ModalComponent isOpend={isOpend} title={title}/>
{children}
</ModalContext.Provider>
}
Run Code Online (Sandbox Code Playgroud)
因此,在创建 ModalContext 组件并将其放在主应用程序组件上方之后,您可以在自己的钩子中提取此上下文功能,如下所示
function useModalContext() {
const context = React.useContext(ModalContext);
// if context is undefined this means it was used outside of its provider
// you can throw an error telling that to your fellow developers
if(!context) {
throw new Error('useModalContext must be used under <ModalContextProvider/>');
}
return context;
}
Run Code Online (Sandbox Code Playgroud)
然后在任何组件中,您可以像这样使用这个钩子
const {setIsOpened, setTitle} = useModalContext();
const handleOpenModal() {
setIsOpened(true);
setTitle('Modal Title');
}
return <button onClick={handleOpenModal}>Show Modal</button>
Run Code Online (Sandbox Code Playgroud)
如果它位于上下文提供程序组件下,您可以在应用程序中的任何位置使用它。
| 归档时间: |
|
| 查看次数: |
1942 次 |
| 最近记录: |