【问题标题】:I got an error for using React.useRef inside a react function component我在反应函数组件中使用 React.useRef 时出错
【发布时间】:2020-06-14 05:40:34
【问题描述】:

我在反应功能组件中使用 React.useRef,在我在类组件中使用它之前收到错误消息,现在我已将其更改为反应功能组件,但我仍然在下面收到此错误消息.

React Hook "React.useRef" 在函数 "landingPage" 中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数

您能否解释一下为什么我在放入功能组件后仍然收到此消息。这是我的代码

import React from "react";
import Modal from "./Modal";

function landingPage() {
  const modalRef = React.useRef();

  return (
    <div className="landingPage">
      <div className="container">
        <div className="landingPage__row">
          <div className="playvideo-wrapper">
            <div className="playvideo-text">See us in action</div>
            <div className="playvideo-button" onClick={openModal}>
              <p>Play Video</p>
            </div>
            <Modal ref={modalRef}>
              <iframe
                src="https://www.youtube.com/embed/SQ8CvT25_Dg?autoplay=1"
                frameborder="0"
                allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
                allowfullscreen
              ></iframe>
            </Modal>
          </div>
        </div>
      </div>
    </div>
  );
}

export default landingPage;

这是我在 app.js 中的代码

import React, { Component } from "react";
import LandingPage from "./LandingPage";

export default class App extends Component {
  render() {
    return (
      <div className="main">
        <LandingPage />
      </div>
    );
  }
}

【问题讨论】:

标签: reactjs react-hooks use-ref


【解决方案1】:

React 组件必须以大写字母开头。改变这个:

function landingPage() {...

到这里:

function LandingPage() {...

【讨论】:

  • 否则 React 认为它只是一个普通的 Javascript 函数,并且这些钩子是不允许的
  • @CodeNinja 不用担心。如果这为您解决了所有问题,请将其标记为正确答案:)
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多