如何将接口对象和其他类型的对象传递给 React 中的功能组件?

How to pass an object of an interface and some other type to functional component in React?

假设我有一个接口

interface Setting {
    desc: string,
    title: string,
    value: string | number | boolean | number[] | float,
    value_type: "string" | "integer" | "bool" | "list" | "float"
}

以及接受两个参数的功能组件

const SettingsOption = ({ ...option }: Setting, test: string): JSX.Element => {return (...)}

这样的函数签名对 TypeScript 编译器来说似乎没问题。

接下来,我尝试使用 <SettingsOption {...option} test=""/> 调用组件,但它显示

type '{ test: string; desc: string; title: string; value: string | number | boolean | number[]; value_type: "string" | "float" | "integer" | "bool" | "list"; }' is not assignable to type 'IntrinsicAttributes & Setting'.
  Property 'test' does not exist on type 'IntrinsicAttributes & Setting'.ts(2322)

我的问题:有没有办法通过传递所有必要信息来调用此类组件?

有几点你必须注意。

  1. 在 React 函数式组件中,第一个参数是组件属性,第二个参数是 Forwarding refs to DOM components
  2. 您在 JSX 元素中传递的所有属性将在组件中接收为 porps

所以第二个参数不能有 test。此外,如果您使用 test 作为 JSX 元素中的属性,SettingsOption 将在 props 中获取它。因此,您会收到该错误。

interface Setting {
    desc: string,
    title: string,
    test: string;
    value: string | number | boolean | number[] | float,
    value_type: "string" | "integer" | "bool" | "list" | "float"
}
const SettingsOption = ({ ...option }: Setting): JSX.Element => {return (...)}

或者不使用功能组件作为元素,您可以将其作为函数调用并传递所有必要的参数:

return (
    <div>
        {SettingsOption(option, "test")}
    </div>
)

但是如果您的组件使用了 hooks,这种方法可能会导致 Rendered more times than during previous render 上升。

你不能这样做,因为第一个参数是 props 对象,第二个参数是 React.forwardRef API 的引用。但是你可以使用 rest 运算符,例如:

interface Setting {
    desc: string,
    title: string,
    value: string | number | boolean | number[] | float,
    value_type: "string" | "integer" | "bool" | "list" | "float",
    test: string
}
const SettingsOption = ({test, ...option }: Setting): JSX.Element => {return (...)}