【问题标题】:React children[] issue with TypeScript用 TypeScript 反应 children[] 问题
【发布时间】:2019-02-15 13:32:12
【问题描述】:

我有一个组件Radio

import { RadioItemProps } from './Item';

type Props = {
  children: ReactElement<RadioItemProps>[];
};

export default function Radio(props: Props) {
  return props.children;
}

还有一个组件 RadioItem 应该是 Radio 的直接子代:

export type RadioItemProps = {
  value: string;
  children: ReactText;
};

export default function RadioItem(props: RadioItemProps) {
  return <input type="radio" name="xxx" value={props.value} />;
}

当我使用它们时:

<Radio>
  <RadioItem value="option-1">Option 1</RadioItem>
  <RadioItem value="option-1">Option 1</RadioItem>
</Radio>

我遇到了 TypeScript 错误:JSX element type 'ReactElement&lt;RadioItemProps, ...&gt;[]' is missing the following properties f rom type 'Element': type, props, key

如果我将孩子类型更改为ReactElement&lt;RadioItemProps&gt;,并且只添加一个孩子,它就可以工作。但是一旦我把数组,我得到了这个错误。

我错过了什么?

"typescript": "^3.2.2",
"react": "16.7.0-alpha.2",
"react-dom": "16.7.0-alpha.2",
"@types/react": "^16.8.3",
"@types/react-dom": "^16.0.11",

【问题讨论】:

    标签: javascript arrays reactjs typescript children


    【解决方案1】:

    我刚刚发现了问题...这是因为:

    export default function Radio(props: Props) {
      return props.children;
    }
    

    我不得不把它改成:

    export default function Radio(props: Props) {
      return (
        <Fragment>{props.children}</Fragment>
      )
    }
    

    似乎无法直接返回子项(类型为数组)。这很奇怪,因为这行得通:

    export default function Radio(props: Props) {
      return ['lol'];
    }
    

    这是一个棘手的问题......

    【讨论】:

    • 我输入我的函数组件为React.FunctionComponent&lt;Props&gt;,这里是一个example React.FunctionComponent&lt;Props&gt; 应该返回一个ReactElement
    • 在我进行更改之前,sandbox.io 链接中的类型检查似乎对我不起作用,因此只需在代码中添加和删除行/空格或其他内容。
    • 在花了一个小时试图弄清楚如何正确使用带有 React.FunctionalComponent 和 typescript 的 children 道具后,我通过添加片段标签解决了这个问题,因为 FC 需要返回一个特定类型不同于儿童类型
    猜你喜欢
    • 2019-07-01
    • 2021-07-08
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    相关资源
    最近更新 更多