React:使用状态有条件地渲染功能组件 |不是函数错误

React: Conditional rendering of functional components using state | is not a function error

您好,我正在尝试有条件地渲染单页游戏的三个方面之一,但我遇到了第一个障碍。

import React, { useState } from "react";

function App() {
  const [currentPage, setCurrentPage] = useState("Intro");


  if (currentPage === "Intro") {
    return (
      <div className="App">
        <Intro setCurrentPage={setCurrentPage} />
      </div>
    );
  }
  if (currentPage === "GameContainer") {
    return (
      <div>
        <GameContainer  setCurrentPage={setCurrentPage} />
      </div>
    );
  }
  if (currentPage === "EndGame") {
    return (
      <div>
        <EndGame  setCurrentPage={setCurrentPage} />
      </div>
    );
  }
}

export default App;

这可以很好地渲染组件,但是有一个按钮我已经连接到介绍组件中的点击功能,我希望它会改变状态,从而改变渲染。

import React from "react";

function Intro(setCurrentPage) {
  function startGame() {
     setCurrentPage("GameContainer");
  }

  return (
    <div className="intro">

      <div class="hoverButton">
        <button class="startButton" onClick={startGame} alt="start game">
          Start Game!
        </button>
      </div>
      <p id="footNote">written using react.js</p>
    </div>
  );
}

export default Intro;

我收到错误“setCurrentPage 不是函数”。

我知道那里有资源,但我就是不知道如何实现我的目标或理解我哪里出错了?

如有任何建议,谢谢

您在 Intro 中错误地解构了道具 setCurrentPage。在直接解构道具时,您应该添加花括号,在您的情况下,{setCurrentPage}.

尝试将其更新为:

import React from "react";

function Intro({setCurrentPage}) {
  function startGame() {
     setCurrentPage("GameContainer");
  }

  return (
    <div className="intro">

      <div class="hoverButton">
        <button class="startButton" onClick={startGame} alt="start game">
          Start Game!
        </button>
      </div>
      <p id="footNote">written using react.js</p>
    </div>
  );
}

export default Intro;