【问题标题】:React Typescript - InferProps accepts null but JSX Attributes does not (i.e. id)React Typescript - InferProps 接受 null 但 JSX 属性不接受(即 id)
【发布时间】:2021-01-31 17:39:37
【问题描述】:

我正在开始一个新的 Typescript 和 React 项目,我在这两种语言方面都有经验,但事实证明将它们结合起来相当困难。

我现在面临的问题是,当我想接收一个 id 用作道具并使用 PropTypes 定义时,当我使用 InferProps 获取组件的类型时,它会将 id 类型显示为“string | null | undefined" 并且 div 组件只接受 "string | null"。

import PropTypes, { InferProps } from 'prop-types';

export function TestComponent({ id }: InferProps<typeof TestComponent.propTypes>) {
  return <div id={id}></div>;
}

TestComponent.propTypes = {
  id: PropTypes.string
};

我想过直接在 PropTypes.string 中更改类型,但一定有更好的解决方案。

感谢您的帮助。

【问题讨论】:

    标签: reactjs typescript react-proptypes


    【解决方案1】:

    你应该有prop类型

    TestComponent.propTypes = {
      id: PropTypes.string.isRequired | undefined
    };
    

    isRequired 使 prop 为非 null 且非未定义。

    这样 Id 就不会为空。

    注意:未测试。

    【讨论】:

    • 我不希望它是必需的,我不介意它是未定义的,因为有时这个组件不需要 ID,我只是希望它不为空,所以它的类型,当不需要时,是“string | undefined”,这样它就匹配了 JSX 属性 id 的类型
    • 在 PropTypes 中,我们可以通过将其设为 isRequired 来指定非空和非未定义,但不能单独指定为非空。 id: PropTypes.string.isRequired | undifined 试试这个,它是字符串和未定义但不为空
    • 此代码示例无法编译,它不是有效的 TS 语法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 2022-11-16
    • 2021-03-09
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多