簡體   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