reactjs 如何在react中的特定元素上呈现组件

rbl8hiat  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(103)

我的react函数组件为:

import React from "react";
import { ReactDOM } from "react";
import { useState } from "react";
import Cart from "./components/cart";

function Shop() {
  const [showCart, setShowCart] = useState(false);
  const cartPreview = (e) => {
    console.log(e.target.parentElement.parentElement);
    ReactDOM.render(<Cart />, e.target.parentElement.parentElement);
    setShowCart(!showCart);
  };
}

下面是cartPreview功能的按钮:

<div className="flex justify-center m-auto w-full">
  <button
    onClick={cartPreview}
    className="hover:bg-green-800 shadow-md bg-green-900 text-gray-100 rounded-md p-2 h-10"
  >
    Add To Cart
  </button>
</div>

显示运行时错误:TypeError: Cannot read properties of undefined (reading 'render')
我想在包含cartPreview按钮的div上呈现cart组件。

相关问题