javascript TypeScript -类型“Element”不可分配给类型“ReactChildren”

olhwl3o2  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(230)

我被卡住了,不知道如何解决这个错误了。
下面是我的应用程序组件的代码

const App = () => (
  <Root>
    <Layout>
      <Router history={history}>
        <Navbar />
        <Switch>
          {routingConfig.map((page: RouteElement, idx: number) => {
            const { exact, path, component } = page
            return <Route key={idx} exact={exact} path={path} component={component} />
          }
          )}
        </Switch>
      </Router>
    </Layout>
  </Root>
)

我得到的错误(同样的错误发生在两个组件-布局和路由器):

> Type 'Element' is not assignable to type 'ReactChildren |
> (ReactChildren & string) | (ReactChildren & number) | (ReactChildren &
> false) | (ReactChildren & true) | (ReactChildren & ReactElement<...>)
> | (ReactChildren & ReactNodeArray) | (ReactChildren & ReactPortal)'.  
> Type 'Element' is not assignable to type 'ReactChildren &
> ReactPortal'.
>     Type 'Element' is missing the following properties from type 'ReactChildren': map, forEach, count, only, toArray  TS2322
> 
>     14 | const App = () => (
>     15 |   <Root>
>   > 16 |     <Layout>
>        |     ^
>     17 |       <Router history={history}>
>     18 |         <Navbar />
>     19 |         <Switch>

    15 |   <Root>
    16 |     <Layout>
  > 17 |       <Router history={history}>
       |       ^
    18 |         <Navbar />

布局组件编码:

interface Props {
    children: React.ReactChildren
}

const Layout: React.FC<Props> = ({ children }) => <div className="layout">{children}</div>

当我在布局组件上方添加ts-ignore时,不同的错误似乎会出现在根组件上

Type '{ children: (string | Element)[]; }' is not assignable to type 'Props'.
  Types of property 'children' are incompatible.
    Type '(string | Element)[]' is missing the following properties from type 'ReactChildren': count, only, toArray  TS2322

    13 | 
    14 | const App = () => (
  > 15 |   <Root>
       |    ^
    16 |     //@ts-ignore
    17 |     <Layout>
    18 |       <Router history={history}>

根组件代码:

interface Props {
    children: React.ReactChildren
}

export const Root: React.FC<Props> = ({ children }) => (
    <Provider store={store}>
        {children}
    </Provider>
)

不知道为什么在某个时候返回Element类型。任何提示都将不胜感激。

bmp9r5qi

bmp9r5qi1#

看起来你的Layout children props应该是child或element,因为你只有一个child:

interface Props {
  children: React.ReactChild
}
sdnqo3pr

sdnqo3pr2#

ReactChild已弃用。使用ReactNode

interface Props {
    children: React.ReactNode
}

相关问题