1

我在反应中使用 Chakra UI,当我尝试单击可点击框中的按钮时,正在执行框的功能。Z-index 也没有解决这个问题。

我的代码:

<Box
   w="90%"
   h="auto"
   mt="10px"
   position="relative"
   key={index}
   borderWidth="1px"
   borderRadius="lg"
   onClick={() =>
   history.push(`/products/${item.cat_name}/${item.id}`)}
>
 <h1 className={styles.heading_bold}>{item.cat_name}</h1>
<Button position="absolute" top="3" right="3" zIndex="0"> //Button not able to click
 Options
</Button
</Box>

代码沙盒链接

4

1 回答 1

5

它不应该是onClickonclick。

   <Button
        onClick={() => console.log("button clicked")} // Typo fixed
        position="absolute"
        top="3"
        right="3"
        zIndex="0"
      >

这是CodeSandbox: https://codesandbox.io/s/debuuge-lwio5

另请注意,Button is在第Box一个Button处理程序内部被调用,然后在Box单击按钮后处理程序也被调用。

要阻止事件传播,您可以使用以下代码。

  <Button
        onClick={(e) => {
          e.stopPropagation();
          console.log("button clicked");
        }}
        position="absolute"
        top="3"
        right="3"
        zIndex="0"
      >

现在,每当您单击 Button 时,只会调用它的处理程序,您将button clicked在输出中看到。

于 2021-01-02T08:47:17.160 回答