【问题标题】:How to use Render Props in functional component using typescript如何使用 typescript 在功能组件中使用渲染道具
【发布时间】:2020-08-29 01:07:41
【问题描述】:

我正在尝试将我的 React 应用程序 (create-react-app) 转换为使用 Typescript,但我遇到了一个使用渲染道具的组件的障碍。

这是一个简化的版本,仍然有错误...

import React from 'react'

type Props = {
    fullWidth?: boolean,
    renderRightSection?: React.ReactNode
}

const Component = React.forwardRef<HTMLInputElement, Props>((props, ref) => {

    let {fullWidth, renderRightSection, ...inputProps} = props

    return (

        <InputWrapper fullWidth={props.fullWidth}>

            <input {...inputProps} ref={ref} />

            {renderRightSection && renderRightSection()}

        </InputWrapper>

    )

})

错误在于 renderRightSection() 位,如下所示:

let renderRightSection: string | number | true | {} | React.ReactElement<any, string | ((props: any) => React.ReactElement<any, string | ... | (new (props: any) => React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<...>)> | React.ReactNodeArray | React.ReactPortal
This expression is not callable.
  No constituent of type 'string | number | true | {} | ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)> | ReactNodeArray | ReactPortal' is callable.ts(2349)

任何帮助将不胜感激。

编辑:

展示我如何在表单中使用组件:

<Textbox 
    name="username" 
    type="text" 
    fullWidth={true} 
    placeholder="Choose a Username" 
    renderRightSection={() => (
        <TextboxBadge>
            {usernameAvailable && <span>Available</span>}
            {!usernameAvailable && <span>Taken</span>}
        </TextboxBadge>
    )}
/>

编辑:

这就是它的用途,在文本框的右侧渲染一个 JSX 块。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    我解决了这个问题。似乎在为组件创建类型时,渲染道具需要是一个返回 JSX 的函数。我不知道你可以这样做:

    type Props = {
        fullWidth?: boolean,
        className?: string,
        renderRightSection?: () => JSX.Element
    }
    

    但它奏效了!

    【讨论】:

    • 谢谢你,拯救了我的一天。我正在使用 React.FC 创建组件,但它不起作用。
    猜你喜欢
    • 2020-04-16
    • 2016-05-06
    • 2020-07-29
    • 2021-10-22
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2019-07-18
    相关资源
    最近更新 更多