反应,将状态从子组件传递到父组件

React, passing state from a Child component to the Parent

我刚刚在学习 React 并且 运行 遇到了一个问题。我正在制作一堆如下所示的计数器组件:

问题是我已经在每个计数器中定义了状态,其中有 3 个,我想将值(数字)传递给父级,这样我就可以将它加起来并显示总计数.

这是我的子计数器组件:

import React, { useState } from "react";
const Counter = () => {
    const [count, setcount] = useState(0)
    const handleIncrement=()=>{

        setcount(count+1);
    }
    const handleDecrement=()=>{

        setcount(count+-1);
    }

  return (
    <div>
      <button onClick={()=>{handleIncrement()}}>+</button>
      <span>{count}</span>
      <button onClick={()=>{handleDecrement()}}>-</button>
    </div>
  );
};

export default Counter;

这是我想将我的值传递给的父项,这样我就可以将它们相加并显示总数:

import React from 'react'
import Counter from './Counter'
const Counters = () => {
  return (
    <>
    <h3>totalcount:</h3>
    <Counter/>
    <Counter/> 
    <Counter/> 

    </>
  )
  
}

export default Counters

我尝试的是制作多个状态,但我找不到制作这个的好方法。我知道对此有一个简单的答案,但我把它弄得太复杂了。如果你们对我的代码有其他优化,请分享。

在 React 状态下从上到下。如果父级中定义的函数已作为 props 传递给嵌套组件,则嵌套组件可以更新父级的状态。这意味着,你想做的事情是不可能的,因为你的代码已经设置好了。实现您正在寻找的方法是:

import React, { useState } from "react";
const Counter = ({count, setCount}) => {
  
    const handleIncrement=()=>{
        setCount(count+1);
    }
    const handleDecrement=()=>{
        setCount(count+-1);
    }

  return (
    <div>
      <button onClick={()=>{handleIncrement()}}>+</button>
      <span>{count}</span>
      <button onClick={()=>{handleDecrement()}}>-</button>
    </div>
  );
};

export default Counter;
import React, { useState } from 'react'
import Counter from './Counter'
const Counters = () => {
  const [countOne, setCountOne] = useState(0)
  const [countTwo, setCountTwo] = useState(0)
  const [countThree, setCountThree] = useState(0)
  return (
    <>
    <h3>totalcount: {countOne + countTwo countThree} </h3>
    <Counter count = {countOne} setCount = {setCountOne} />
    <Counter count = {countTwo} setCount = {setCount} />
    <Counter count = {countThree} setCount = {setCountThree} />

    </>
  )
  
}

export default Counters