我正在用react将我的js
项目重写为typescript
,并且我有以下函数来创建我试图重写的dataContext
:
javascript version
import React, {useReducer} from 'react'
export default (reducer, actions, defaultValue) => {
const Context = React.createContext()
const Provider = ({children}) => {
const [state, dispatch] = useReducer(reducer, defaultValue)
const boundActions = {}
for (let key in actions) {
boundActions[key] = actions[key](dispatch)
}
return (
<Context.Provider value={{state, ...boundActions}}>
{children}
</Context.Provider>
)
}
return {Context, Provider}
}
这是我的typescript version
import React, {useReducer, createContext, ReactNode} from 'react'
export default (reducer: any, actions: any, defaultValue: any) => {
const Context = createContext(defaultValue)
const Provider = (children: ReactNode) => {
const [state, dispatch] = useReducer(reducer, defaultValue)
const boundActions: any = {}
for (let key in actions) {
boundActions[key] = actions[key](dispatch)
}
return (
<Context.Provider value={{state, ...boundActions}}>
{children}
</Context.Provider>
)
}
return {Context, Provider}
}
我遇到以下错误,我不知道如何解决。我在children
上尝试了一些其他类型,如ReactNode[]
、JsxElement[]
、Element[]
等,但都不起作用。
Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & ReactNode'.
Type '{ children: Element; }' is missing the following properties from type 'ReactPortal': key, type, props
1路
const Provider: React.FC = ({ children }) => {...}
双向
interface IProviderProps extends React.PropswithChildren {}
const Provider: React.FC<IProviderProps> = ({ children }) => {...}
3路
interface IProviderProps {
children?: ReactNode | undefined;
}
const Provider: React.FC<IProviderProps> = ({ children }) => {...}