【问题标题】:How to define props interface with passed state/setState values?如何使用传递的 state/setState 值定义 props 接口?
【发布时间】:2021-06-28 13:30:11
【问题描述】:

我目前正在学习 TypeScript,在我的应用程序中发现了一个问题,将 React.FunctionComponent 添加到我的组件后,我的 Props 界面出现错误

Type '({ value, setValue, }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
   Types of parameters '__0' and 'props' are incompatible.
      Type '{ children?: ReactNode; }' is missing the following properties from type 'Props': value, setValue ts(2322)

我的代码中有一部分:

interface Props {
    value: string
    setValue: React.Dispatch<React.SetStateAction<string>>
    children: React.ReactNode
}

const SearchInput: React.FunctionComponent = ({
    value,
    setValue,
}: Props) => {}

我尝试仅使用 ReactNode,我尝试使用 JSX.Element,但没有任何效果,有人可以解释一下问题出在哪里以及如何解决吗?

【问题讨论】:

  • 从界面中移除子元素,并像这样定义 SearchInput:const SearchInput: React.FC&lt;Props&gt; = ({value, setValue}) =&gt; {}

标签: reactjs typescript next.js


【解决方案1】:

React.FunctionComponent 是一个通用组件,你需要将你的Props 传递给它:React.FunctionComponent&lt;Props&gt;。这也允许您省略函数参数的类型注释,因为它可以自动派生:

const SearchInput: React.FunctionComponent<Props> = ({
    value,
    setValue,
}) => {}

【讨论】:

    猜你喜欢
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2017-11-05
    • 2022-11-10
    • 2021-01-14
    • 2023-01-09
    相关资源
    最近更新 更多