简体   繁体   中英

React: How to extract values from Modals?

I have a Chakra UI Modal which opens up onClick of a button. I want to be able to extract the values that a user puts into the inputs/radio buttons when they close the Modal. The Modal class and the Modal/Button render is shown below. Since the input and radio buttons are defined within the Modal class, is it possible to get their final values onClose ?

Modal.tsx

 import React from 'react' import { Modal as ChakraModal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton, RadioGroup, Stack, Radio, VStack } from "@chakra-ui/react" import Button from './Button' import Input from './Input' type Props = { isOpen: boolean } & { onClose: () => void} & { label: string } const Modal = ({ label, isOpen, onClose, ...rest }: Props) => ( <ChakraModal {...rest} isOpen={isOpen} onClose={onClose}> <ModalOverlay /> <ModalContent> <ModalHeader>{label}</ModalHeader> <ModalCloseButton /> <ModalBody> <VStack spacing={4}> <RadioGroup> <Stack direction="row"> <Radio value="1">Annually</Radio> <Radio value="2">Semi-Annual</Radio> <Radio value="3">Quarterly</Radio> <Radio value="4">Monthly</Radio> </Stack> </RadioGroup> <Input label="Custom Interest rate" name="Custom Interest rate" /> </VStack> </ModalBody> <ModalFooter> <Button colorScheme="blue" mr={3} onClick={onClose}> Save </Button> </ModalFooter> </ModalContent> </ChakraModal> ) export default Modal

Render

 <Button onClick={onOpen}> Settings </Button> <Modal label="Custom Settings" isOpen={isOpen} onClose={onClose} />

You should probably send a state as the modal's prop.

const [state, setState] = React.useState();
<Modal 
  label="Custom Settings"
  isOpen={isOpen} 
  onClose={onClose}
  onChange={setState}
/>

To get the type of setState, hover over the variable and you can see the type definition.

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