我正在尝试将我的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。
答案 0 :(得分:1)
我解决了这个问题。似乎在为组件创建类型时,渲染道具需要是一个返回JSX的函数。我不知道您可以这样做:
type Props = {
fullWidth?: boolean,
className?: string,
renderRightSection?: () => JSX.Element
}
但是有效!