问题描述
我正在尝试使用TypeScript和Context API来创建待办事项应用程序,但不能将use-to-do上下文与useContext Hook一起使用。
创建上下文, 在这里,我创建了一个待办事项数组的接口并创建了它的上下文。
const todos = [
{ todo: 'Make Break Fast',id: 1,completed: true },{ todo: 'React Book',id: 2,completed: false },{ todo: 'Start Coding',id: 3,]
interface ITodos {
todo: string
id: number
completed: boolean
}
export const TodoContext = createContext<ITodos[]>(todos);
全球提供商, 在这里,我创建了上下文提供程序,并将其子级(JSX.Elements)传递为道具。
interface IChildrenProp {
children: React.ReactNode
}
const ContextProvider = ({ children }: IChildrenProp): JSX.Element => {
return <TodoContext.Provider value={todos}>
{children}
</TodoContext.Provider>
}
export default ContextProvider;
使用上下文, 在这里,我期望使用TodoContext中的useCotext Hook来完成待办事项。
import React,{ useContext } from 'react'
import TodoContext from './store/context'
const Todo: React.FC = (): JSX.Element => {
const todos = useContext(TodoContext)
return (
<>
<h1>My Todo List</h1>
<input id='todo' placeholder='e.g. Read Book' />
</>
)
}
export default Todo
TypeScript error in /typescript/todo-app/src/Todo.tsx(9,30):
Argument of type '({ children }: IChildrenProp) => JSX.Element' is not assignable to parameter of type 'Context<unkNown>'.
Type '({ children }: IChildrenProp) => Element' is missing the following properties from type 'Context<unkNown>': Provider,Consumer TS2345
7 | const Todo: React.FC = (): JSX.Element => {
8 |
> 9 | const todos = useContext(TodoContext)
| ^
10 |
11 |
12 | return (
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)