【问题标题】:React - Calling function from another function does not workReact - 从另一个函数调用函数不起作用
【发布时间】:2022-01-07 02:58:15
【问题描述】:

我有一个用 React 代码编写的游戏,它分为两部分:第一部分定义游戏是简单还是困难。第二部分是游戏本身

Function App() {
    return (
        <>
        <div><First/></div> 
        <div'><Second/></div>
        </>
    )
}

export default Main

在第一部分,用户单击一个按钮来定义级别。这应该会对第二部分产生影响。这是我写的。

First.js:

import React from 'react'
import { useState } from "react";
import '../paginas/ind.css'
import Second from './Second';


function First() {
    const [Difficulty,setdifficulty] = useState(1)


    function easy(e){ 
        setdifficulty(1)
        Second(1)
      }

    function hard(e){ 
        setdifficulty(2)
        Second(2)
      }  
    return (
        <>
        {Difficulty !== 1 ? <div onClick={easy}>Easy</div> :
        <div>Easy</div>} 
        {Difficulty !== 2 ?<div onClick={hard}>Medium</div>:
        <div>hard</div>}
        </>
    )
}

export default Izq

Second.js:

import React from 'react'
import '../paginas/ind.css'
import Difficulty from './First'
import First from './First '

function Second (Difficulty) {
console.log(Difficulty)
    return (
        <>
        {Difficulty === 1 ? <div>This game is going to be easy</div>:<div></div>}
        {Difficulty === 2 ? <div>This game is going to be hard</div>:<div></div>}
        </>
    )

}

export default Central

我不知道为什么,但是当我在第一个脚本上单击“简单”或“困难”时,第二个脚本没有任何反应。通过在 Second.js 上使用 console.log(Difficulty),我可以知道变量“Difficulty”的值发生了变化。但是条件“{Difficulty === 1 ? This game will be easy:}”假设它的值是cero。我找不到任何意义。请帮帮我。

谢谢

【问题讨论】:

  • 你没有在任何地方使用你的Second组件。

标签: javascript reactjs function


【解决方案1】:

你必须先了解react的基础知识,如何正确传递props和states,context api在react中的使用等等。我建议你先看一些教程。

话虽如此,如果您像下面这样更改AppFirstSecond 组件的功能,您将得到结果。这只是最简单的方法。

function First() {
  const [Difficulty, setdifficulty] = useState(1);
  return (
    <>
      {Difficulty !== 1 ? (
        <div onClick={(e) => setdifficulty(1)}>Easy</div>
      ) : (
        <div>Easy</div>
      )}
      {Difficulty !== 2 ? (
        <div onClick={(e) => setdifficulty(2)}>Medium</div>
      ) : (
        <div>hard</div>
      )}
      <Second Difficulty={Difficulty} /> // You will have to import the second component into this page. And remove it from App
    </>
  );
}

function Second(props) {
  const { Difficulty } = props;
  return (
    <div>
      {Difficulty === 1 && <div>This game is going to be easy</div>}
      {Difficulty === 2 && <div>This game is going to be hard</div>}
    </div>
  );
}

function App() {
  return (
    <div>
      <First />
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多