繁体   English   中英

如何在反应中操作子组件的父组件 state

[英]How to manipulate state of parent component from child in react

我正在尝试制作一个反应游戏。 我有一个将硬币数量增加 1 的组件。但是,我希望能够将它发送到另一个组件以便可以使用它。 示例:购买升级,并减去金币数量。

我怎样才能做到这一点?

游戏.jsx

export default function Game() {
    // set state to bet that of the Counter when it is updated



    const element = (
        <div className="app">
            <Counter />
            <UpgradeMenu />
        </div>
    );
    return element;
}

计数器.jsx

export default function Counter() {
    const [count, setCount] = useState(0);

    const increment = () => {
        setCount(count + 1);
    };

    const element = (
        <div className="section">
            <div className="counter">
                <h1>{count} coins</h1>
                <button onClick={increment}>Click</button>
            </div>
        </div>
    );
    return element;
}

提前谢谢你,我希望这能理解我正在尝试做的事情。

对于这种情况,我们可以将 state 移动到父级( Game组件),然后Counter组件将接收countonClick道具。

import { useState } from "react";

export default function Game() {
  const [count, setCount] = useState(0); // move the state here

  function handleClick() { // this function will be passed to Counter component
    setCount(count + 1);
  }

  const element = (
    <div className="app">
      <Counter count={count} onClick={handleClick} />
    </div>
  );
  return element;
}

export function Counter({ count, onClick }) {
  const element = (
    <div className="section">
      <div className="counter">
        <h1>{count} coins</h1>
        <button onClick={onClick}>Click</button>
      </div>
    </div>
  );
  return element;
}

检查这个工作示例: https://codesandbox.io/s/so-72469269-mehsdp?file=/src/App.js

这可以是一个很好的参考:

您可以将 function 作为子元素的属性传递并在其中运行 function。

家长:

export function parentElement(){
  function myfunction() {return true}
    return(
      <chlidrenElement myFunction={myfunction}>
    )
  }
}

孩子们:

export function childrenElement({myFunction}){
  const hidden = myFunction();
  return(
    {
      hidden ?
      <chlidrenElement myFunction={myfunction}>
      : null
    }
  )
}

暂无
暂无

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

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