包装Reaction组件的子项,该组件的子项被限制为特定类型 [英] wrap children for react component which has children restricted to certain types

查看:0
本文介绍了包装Reaction组件的子项,该组件的子项被限制为特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个组件限制为具有使用流类型的某些类型的子项。但是,现在我有几种情况,可以方便地将这些组件包装在其他组件中,这些组件只返回一个有效组件,但附加了一些缺省值。即使使用Reaction片段对其中一些有效组件进行分组,也会产生无法调试的奇怪错误。

这里有一段示例代码(that you can run on flow playground)

//@flow
import React from 'react'
import type { Node, Element, ChildrenArray } from 'react'

type ItemType = Element<typeof ListItem | typeof ListHeader>

type Props = {
  children: ChildrenArray<ItemType>,
}

function List({ children }: Props) {
  return <div>{children}</div>
}

type ItemProps = {
  children: Node,
  onClick?: () => void,
}

function ListItem({ children, onClick }: ItemProps) {
  return <div onClick={onClick}>{children}</div>
}

type HeaderProps = {
  children: Node,
}

function ListHeader({ children }: HeaderProps) {
  return <div>{children}</div>
}

const Row = ({ left, right }: { left: string, right: Node }): Node => {
  return (
    <ListItem>
      {left}
      <span>{right}</span>
    </ListItem>
  )
}

const x = () => (
  <List>
    <Row left="gender" right="${gender}" />
    <Row left="birthDate" right="xxx" />
    <Row left="Number" right="xxx" />
    <Row left="sendEnrollmentLetter" right="stuff" />
  </List>
)

遵循这种模式的正确方式是什么?

在Flow操场上您不会看到错误,因为如果您打开控制台,您会看到它刚刚爆炸。

这是我在项目中遇到的具体错误:

Cannot create `List` element because in array element of property `children`: 
Either property `children` is missing in  object type [1] but exists in  `HeaderProps` [2] in property `props`. 
Or property `children` is missing in  object type [1] but exists in  `ItemProps` [3] in property `props`.

推荐答案

在项目上运行代码片段时,内部的子组件出现以下错误x

Cannot create `Parent` element because Could not decide which case to select, since case 1 [1] may work but if it doesn't case 2 [2] looks promising too. To fix add a type annotation to return [3].Flow(incompatible-type)

假设这些都是您收到的错误,Flow无法推断您的组件应该是什么类型,因此它希望您手动对它们进行注释。添加Node的返回类型应该可以

const Wrapper = (): Node => (
  <>
    <Foo disabled />
    <Bar />
  </>
);

const Defaults = (): Node => <Foo disabled={false} />;

const x = (
  <Parent>
    <Wrapper />
    <Wrapper />
    <Defaults />
  </Parent>
);

作为附注,我强烈建议您使用import * as React from 'react';,这样您就可以使用React.Node。否则,来自Reaction的Node将与将来使用的htmlNode冲突。

这篇关于包装Reaction组件的子项,该组件的子项被限制为特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆