简体   繁体   中英

Typescript Interface for Annoymous Function passed into React Component

I am learning to use Typescript with React functional components (a Bootstrap modal component) and became confused with how the Typescript interface should be properly defined for the component when an anonymous function is used.

In this example below, TheModal component is passed in a boolean show and a anonymous function handleClose .

export function Foo(): JSX.Element {
    const [ showModal, setShowModal ] = useState(false);

    return (
        <MyContainer>
            <TheModal show={showModal} handleClose={ () => setShowModal(!showModal) } />
        </MyContainer>
    )
}

Below is the TheModal component and the Typescript interface definition IModal . Although the code runs, I think any should not be used for handleClose .

interface IModal {
    show: boolean;
    handleClose: any;  // <======== I believe we should use something better than `any`
}

function TheModal({show, handleClose}: IModal): JSX.Element {
    return (
        <Modal show={show} onHide={handleClose}>
            <Modal.Header closeButton>
                <Modal.Title>Hello World</Modal.Title>
            </Modal.Header>
            <Modal.Body>
            </Modal.Body>
            <Modal.Footer>
                <Button variant="secondary" onClick={handleClose}>Cancel</Button>
            </Modal.Footer>
        </Modal>
    )
}

What is the correct way of defining the type for handleClose in IModal ?

I believe the best way fo typing handlers is to use React built in types:


import React from 'react';

interface IModal {
    show: boolean;
    handleClose: React.MouseEventHandler<HTMLButtonElement>;
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM