【问题标题】:Typescript - string' is not assignable to type 'FC打字稿 - 字符串'不可分配给类型'FC
【发布时间】:2021-11-10 05:23:15
【问题描述】:

我遇到了错误

Type '(props: PropsWithChildren) => string' 不可分配给 type 'FC'。 类型 'string' 不可分配给类型 'ReactElement | null'.ts(2322)

在使用下面的打字稿功能时,不明白这里的问题,感谢任何帮助,谢谢!

代码如下,

const MoneyAmount: React.FC<{amount : number}> = (props) => {
    return (
        new Intl.NumberFormat("en-US", {
            style: "currency",
            currency: "USD", 
            maximumFractionDigits: 4
        }).format(props.amount))
}

export default MoneyAmount  ;

【问题讨论】:

  • 如果你想嵌入这段代码,请使用三个反引号。在我的回答中看看我是如何做到的

标签: reactjs typescript


【解决方案1】:

看看FC输入:

   type FC<P = {}> = FunctionComponent<P>;

    interface FunctionComponent<P = {}> {
        (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
        propTypes?: WeakValidationMap<P>;
        contextTypes?: ValidationMap<any>;
        defaultProps?: Partial<P>;
        displayName?: string;
    }

这个函数返回ReactElement&lt;any, any&gt; | null

而这又只是一个带有一组属性的jsx

    interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
        type: T;
        props: P;
        key: Key | null;
    }

您需要做的就是将您的返回值包装成span

const MoneyAmount: React.FC<{ amount: number }> = (props) => {
  const text = new Intl.NumberFormat("en-US", {
    style: "currency", currency: "USD", maximumFractionDigits: 4
  })
    .format(props.amount)


  return <span>{text}</span>
}

让我们尝试在没有FC的情况下使用它:

import React from 'react'

const MoneyAmount = (props: { amount: number }) => {
  return (
    new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      maximumFractionDigits: 4
    }).format(props.amount))
}

// Its return type 'string' is not a valid JSX element.
const x = <MoneyAmount amount={42} />

因此,string 只是无效的 JSX

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 2022-01-17
    • 2020-02-07
    • 2019-04-10
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2020-11-15
    相关资源
    最近更新 更多