在我的应用程序中,我希望能够单击一个项目(背景颜色、文本等),弹出一个带有颜色选择器的模式,然后更改项目的颜色。
我遇到的问题是我onClick
为父元素创建了一个处理程序来更新背景颜色,但是当单击父元素中的任何内容时它也会激活。
我在Codesandbox中有一个示例,您可以看到,无论您单击背景还是按钮,当我只想为背景激活颜色选择器时,它都会出现。
如果有人熟悉 Chakra-ui,这是我的代码:
const Navbar = () => {
const [display, setDisplay] = useState('none');
const [color, setColor] = useState('#1A202C');
const [showColorPicker, setShowColorPicker] = useState(false);
const { isOpen, onOpen, onClose } = useDisclosure();
/*
On click, showColorPicker becomes true and isOpen also becomes true
in order to display the modal with a color picker
*/
const handleModalClick = () => {
onOpen();
if (!showColorPicker) {
setShowColorPicker((showColorPicker) => !showColorPicker);
}
};
return (
<div>
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent
bg='gray.600'
style={{ boxShadow: '2px 2px 2px 1px rgba(0, 0, 0, 0.2)' }}>
<ModalCloseButton color='gray.200' />
<ModalBody style={{ borderRadius: '10px' }}>
<Center>
{showColorPicker && (
<ChromePicker
color={color}
onChange={(updatedColor) => setColor(updatedColor.hex)}
/>
)}
</Center>
</ModalBody>
</ModalContent>
</Modal>
// Flex === a div with display flex
<Flex
bg={color}
color='gray.200'
style={{
textTransform: 'uppercase',
fontWeight: 'bold',
}}
onClick={handleModalClick}>
<Link p='5' _hover={{ color: 'cyan.400' }}>
<Text fontSize='xl'>Color Selector</Text>
</Link>
<Spacer />
<Flex
display={['none', 'none', 'flex', 'flex']}
fontSize='md'
align='center'>
<Link p='5' _hover={{ color: 'cyan.400' }}>
About
</Link>
<Link p='5' _hover={{ color: 'cyan.400' }}>
Portfolio
</Link>
<Link p='5' _hover={{ color: 'cyan.400' }}>
Contact
</Link>
</Flex>
</Flex>
...
</div>
);
};
有没有办法仅在单击背景时显示颜色选择器?