【发布时间】:2020-05-25 12:59:51
【问题描述】:
我正在使用 context.provider usecontext reacthook 来显示一个对话框。我在 MainComponent 周围设置了这个。对于 context.provider 的 value 属性,我得到错误类型 {setDialogOpen(Open: boolean) => void} is not assignable to type boolean。
我想做什么? 当用户单击主页或书籍组件中的按钮时,我想显示一个对话框。单击对话框中的隐藏按钮时,不应打开对话框。
下面是我的代码,
function MainComponent() {
const DialogContext = React.createContext(false);
let [showDialog, setShowDialog] = React.useState(false);
return (
<DialogContext.Provider value={{
setDialogOpen: (open: boolean) => setShowDialog(open)}}>//get error
{showDialog && <Dialog DialogContext={DialogContext}/>
<Route
path="/items">
<Home DialogContext={DialogContext}/>
</Route>
<Route
path="/id/item_id">
<Books DialogContext={DialogContext}/>
</Route>
</DialogContext.Provider>
)
}
function Home({DialogContext} : Props) {
const dialogContext= React.useContext(DialogContext);
const handleClick = (dialogContext: any) {
dialogContext.setDialogOpen(true);
}
return (
<button onClick={handleClick(dialogContext)}>button1</button>
)
}
function Books({DialogContext} : Props) {
const dialogContext= React.useContext(DialogContext);
const handleClick = (dialogContext: any) {
dialogContext.setDialogOpen(true);
}
return (
<button onClick={handleClick(dialogContext)}>button2</button>
)
}
function Dialog({DialogContext}: Props) {
return(
<div>
//sometext
<button> hide</button>
</div>
)
}
我尝试过类似下面的方法,
return (
<DialogContext.Provider value={{
setShowDialog(open)}}>//still get a error
{showDialog && <Dialog DialogContext={DialogContext}/>
)
有人可以帮我解决这个问题,或者提供一种更好的方法来使用 usecontext 钩子在主页和书籍组件中单击按钮时显示对话框。谢谢。
【问题讨论】:
标签: javascript reactjs typescript