jon*_*bbs 3 typescript reactjs
我正在尝试将我的 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>
)
})
Run Code Online (Sandbox Code Playgroud)
错误与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)
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激。
编辑:
展示我如何在表单中使用组件:
<Textbox
name="username"
type="text"
fullWidth={true}
placeholder="Choose a Username"
renderRightSection={() => (
<TextboxBadge>
{usernameAvailable && <span>Available</span>}
{!usernameAvailable && <span>Taken</span>}
</TextboxBadge>
)}
/>
Run Code Online (Sandbox Code Playgroud)
编辑:
这就是它的用途,在文本框的右侧渲染一个 JSX 块。
我解决了这个问题。似乎在为组件创建类型时,渲染道具需要是一个返回 JSX 的函数。我不知道你可以这样做:
type Props = {
fullWidth?: boolean,
className?: string,
renderRightSection?: () => JSX.Element
}
Run Code Online (Sandbox Code Playgroud)
但它奏效了!
| 归档时间: |
|
| 查看次数: |
2735 次 |
| 最近记录: |