我正在尝试使用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, completed: false },
]
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 (