Website-Suche

reactjs - Wie man Render Props in einer funktionalen Komponente mit TypeScript verwendet


Ich versuche, meine React-App (create-react-app) auf TypeScript umzustellen, und ich bin auf ein Hindernis bei einer Komponente gestoßen, die Render-Props verwendet.

Hier ist eine vereinfachte Version, die immer noch den Fehler enthält...

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>

    )

})

Der Fehler liegt beim renderRightSection()-Teil und sieht so aus:

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)

Jede Hilfe wäre wirklich sehr geschätzt.

Bearbeiten:

Um zu zeigen, wie ich die Komponente in einem Formular verwende:

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

Bearbeiten:

Und hier wird es verwendet, um einen Block von JSX auf der rechten Seite des Textfeldes darzustellen.

Antwort #1

Ich habe das Problem gelöst. Es scheint, dass beim Erstellen des Typs für die Komponente die Render-Prop eine Funktion sein muss, die JSX zurückgibt. Ich hatte keine Ahnung, dass man das tun kann:

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

Aber es hat funktioniert!

Verwandte Artikel