首页 > 解决方案 > 当我们将 React 与 Typescript 一起使用时,如何有条件地将可选道具传递给组件?

问题描述

当我们将 React 与 Typescript 一起使用时,我们可以定义可选的 props:

interface SomeProps {
  required: string
  optional?: number
}

const SomeComponent = ({ required, optional }: SomeProps): JSX.Element => { ...

当我们稍后使用它时,我们可以传递或省略可选属性:

<SomeComponent required="abc" />
<SomeComponent required="def" optional={1} />

当我们想在没有 Typescript 的情况下使用 React 动态执行此操作时,我们可以将 undefined 传递给可选属性:

<SomeComponent required="ghi" optional={optionalValue ? optionalValue : undefined } />

但是对于 Typescript,这种方式是行不通的。Typescript 转译器会警告我们 typenumber | undefined不可分配给number. 当然,我们可以将它包装在if语句中并重复SomeComponent使用,但这不是最优雅的解决方案......

当我们将 React 与 Typescript 一起使用时,我们如何有条件地将可选的 props 传递给组件?

更新

请再说一遍。我错了。这种方式当然也适用于 Typescript。我没有注意到我的代码中有一些内部结构(这不是问题的一部分)。

标签: javascriptreactjstypescript

解决方案


import React from 'react'

interface SomeProps {
  required: string
  optional?: number
}

const SomeComponent = ({ required, optional }: SomeProps) => null

const x = <SomeComponent required="abc" />
const y = <SomeComponent required="def" optional={1} />

const Foo = (optional?: number) =>
  <SomeComponent required="ghi" optional={optional ? optional : undefined} />

它在操场上工作


推荐阅读