首页 > 解决方案 > 组件的多次使用导致 React is not defined 错误

问题描述

我正在我的应用程序中渲染一个卡片组件。当我只有一张卡时,一切都很好,只要我有多张卡,我就会得到一张ReferenceError: React is not defined

<div className="App">
  <Card />
  <Card />
</div>

我的卡片组件代码如下(样式是使用Emotion完成的):

/** @jsx jsx */

import React, { useRef } from "react";
import { css, jsx } from "@emotion/core";

import useComponentSize from "@rehooks/component-size";

function Card(props: any) {
  const ref = useRef(null);

  let size = useComponentSize(ref);
  let { width } = size;

  const style = css({
    display: "flex",
    flexDirection: width > 600 ? "row" : "column",
    "& div": {
      marginTop: 10,
      flex: 1
    },
    "& img": {
      objectFit: "cover",
      flex: 1
    },
    "& h2": {
      paddingLeft: 10,
      paddingRight: 10
    },
    "& p": {
      paddingLeft: 10,
      paddingRight: 10
    }
  });

  return (
    <div css={style} ref={ref}>
      <img src="ribena.webp" alt="" />
      <div>
        <h2>placeholder</h2>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
          molestiae, vitae esse et dignissimos consequuntur provident eligendi
          labore beatae laboriosam.
        </p>
      </div>
    </div>
  );
}

export default Card;

我已经安装了 NPM 所需的所有依赖项,并将 React 导入到卡片组件和应用程序组件中。我不明白为什么只有一张卡时才定义它,而有两张卡时却没有。

我在项目中使用 Typescript,如果这有所不同,Typescript 严格模式设置为 false。

我使用的唯一不稳定版本是@ionic/react. 也许这导致了问题?或者可能是 Typescript,因为 Typescript 在我的(有限)体验中经常会引起奇怪的问题

我在codesandbox上重新创建了错误是间歇性的,我看到在这个沙箱中重新创建了同样的错误......有时它有时会出错,有时它不会 ‍♂️</p>

在此处输入图像描述

我正在使用rehooks/component-size 包

标签: reactjstypescriptreact-hooks

解决方案


推荐阅读