简体   繁体   English

如何在 react 和 typescript 中使用 context.provider 设置 state?

[英]How to set the state using context.provider in react and typescript?

i am using context.provider usecontext reacthook to show a dialog.我正在使用 context.provider usecontext reacthook 来显示一个对话框。 i set this around MainComponent.我在 MainComponent 周围设置了这个。 For the value attribute of context.provider i get error type {setDialogOpen(Open: boolean) => void} is not assignable to type boolean.对于 context.provider 的 value 属性,我得到错误类型 {setDialogOpen(Open: boolean) => void} is notassignable to type boolean。

what i am trying to do?我想做什么? I want to display a dialog when user clicks either a button in home or books component.当用户单击主页或书籍组件中的按钮时,我想显示一个对话框。 on clicking hide button in dialog the dialog shouldnt be open.单击对话框中的隐藏按钮时,不应打开对话框。

below is my code,下面是我的代码,

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>
    )
 }

I have tried something like below,我尝试过类似下面的方法,

return (
    <DialogContext.Provider value={{ 
        setShowDialog(open)}}>//still get a error
            {showDialog && <Dialog DialogContext={DialogContext}/>
)

Could someone help me fix this or provide a better approach to show the dialog on clicking a button in home and books component using usecontext hook.有人可以帮我解决这个问题或提供更好的方法来显示使用 usecontext 挂钩单击主页和书籍组件中的按钮的对话框。 thanks.谢谢。

There are few issues that you have to fix in your code.您必须在代码中修复一些问题。

  • You are creating context with the default value of false .您正在使用默认值false创建上下文。 Then later you try to override it to an object and hence the type error.然后稍后您尝试将其覆盖为 object 并因此出现类型错误。
  • To fix the issue, create & export the context in separate file/helper.要解决此问题,请在单独的文件/帮助程序中创建和导出上下文。 Don't pass them down as props.不要把它们当作道具传下去。
  • import the context in parent and child components.在父组件和子组件中导入上下文。
  • your handleClick fun in child component is missing an arrow .您在子组件中的handleClick乐趣缺少arrow
  • the button onClick in child component is directly calling the function.子组件中的button onClick直接调用 function。 You should pass just the function reference.您应该只传递 function 参考。

See the updated code with corrections below.请参阅下面更正的更新代码。

context helper上下文助手

...
type ContextProps = { 
    setDialogOpen?: (open: boolean) => void,
  };
export const DialogContext = React.createContext<ContextProps>({});

MainComponent主要组件

import {DialogContext} from '../contextHelper';
function MainComponent() {
    // const DialogContext = React.createContext(false); //<---- remove this
    let [showDialog, setShowDialog] = React.useState(false);
    return (
        <DialogContext.Provider value={{ 
            setDialogOpen: (open: boolean) => setShowDialog(open)}}>
...

Home & Book Component家庭和书籍组件

import {DialogContext} from '../contextHelper';
function Home() {
    const dialogContext= React.useContext(DialogContext);
    const handleClick = () => {
        dialogContext.setDialogOpen(true);
    }
    return ( 
        <button onClick={handleClick}>button1</button>
    )
}

import {DialogContext} from '../contextHelper';
function Books() {
    const dialogContext= React.useContext(DialogContext);
    const handleClick = () => {
        dialogContext.setDialogOpen(true);
    }
    return ( 
        <button onClick={handleClick}>button2</button>
    )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 React Context.Provider 是必需的(或有用的)? - Why Is React Context.Provider Necessary (Or useful)? 我正在尝试使用挂钩来管理Context.Provider的状态 - I am attempting to use hooks to manage the state of Context.Provider 如何访问react Context.Provider值内的另一个函数? - How can I access another function inside the react Context.Provider value? React context.provider不会更改默认值 - React context.provider doesn't change the default value 在 React 中将多个值和设置器对传递给 Context.Provider - Passing multiple value and setter pairs to Context.Provider in React 如何正确使用带有 Typescript 的 React Context Provider? - How to properly use React Context Provider with Typescript? React Native Context - 从渲染之外的 Context.provider 中检索值 function - React Native Context - retrieve the value from Context.provider outside of the render function React - value 属性是必需的<Context.Provider> . 你是拼错了还是忘记通过了? - React - The value prop is required for the <Context.Provider>. Did you misspell it or forget to pass it? 如何创建类似“ context.Provider” /“ context.Consumer”的结构以在机器人应用中传递值? - How to create a `context.Provider`/`context.Consumer`-like structure to pass values in a bot app? 从树外以编程方式设置反应上下文提供者状态 - set react context provider state programatically from outside the tree
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM