我只是在学习如何应对并遇到问题.我正在制作一组计数器组件,如下所示:
问题是,我已经在每个计数器中定义了状态,即其中的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
我试着做了多个状态,但我找不到一个好方法.我知道这有一个简单的答案,我把它弄得太复杂了.如果你们对我的代码有其他优化,请分享.