简体   繁体   English

React:使用 state 对功能组件进行条件渲染 | 不是 function 错误

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

Hi so i am trying to conditionally render one of three aspects of a one page game and i am stuck at one of the first hurdles.嗨,所以我正在尝试有条件地呈现单页游戏的三个方面之一,但我被困在了第一个障碍中。

 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;

This renders the component fine but there is a button which i have hooked up to an on click function in the intro component which i am hoping would change the state and hence the render.这使组件很好,但是我已经连接了一个按钮,我在介绍组件中连接了一个单击 function,我希望它会改变 state 并因此改变渲染。

 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;

I get the error "setCurrentPage is not a function".我收到错误“setCurrentPage 不是函数”。

I know the resources are out there but i just can't figure out how to achieve what I am aiming for or understand where I am going wrong?我知道资源在那里,但我就是不知道如何实现我的目标或理解我哪里出错了?

Any advice appreciated, thank you任何建议表示赞赏,谢谢

You are destructuring the prop setCurrentPage incorrectly in Intro .您在Intro中错误地解构了道具setCurrentPage You should add curly braces when destructuring the prop directly, in your case, {setCurrentPage} .在直接解构道具时,您应该添加花括号,在您的情况下是{setCurrentPage}

Try updating it as:尝试将其更新为:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM