【发布时间】:2021-11-05 17:44:27
【问题描述】:
我正在构建我的第一个 React 应用程序,我对如何在组件之间进行通信有点困惑。
应用程序计算某个游戏的玩家的分数。为此,我创建了一个组件数组,然后我需要对父组件中每个组件的分数求和。
各个组件的代码如下:
家长:
const RouteScore = () => {
const routes = [
{ length: 1, score: 1 },
{ length: 2, score: 2 },
{ length: 3, score: 4 },
{ length: 4, score: 7 },
{ length: 6, score: 15 },
{ length: 8, score: 21 },
]
const buttons = routes.map((route) => <RouteScoreButton length={route.length} score={route.score} key={route.length} />)
return (
<div className="position-absolute top-50 start-50 translate-middle">
<div className="bg-light border border-primary rounded-3 px-4 py-4 opacity-75 text-center">
<table className="table">
<thead>
<tr className="text-center">
<th scope="col">Route length</th>
<th scope="col">Total routes</th>
<th scope="col">Total score</th>
</tr>
</thead>
<tbody className="text-center align-middle">
{buttons}
</tbody>
</table>
<h3>Total score:</h3>
</div>
</div>
)
}
儿童:
const RouteScoreButton = (props) => {
const [numberRoutes, setNumberRoutes] = useState(0)
const score = useMemo(() => props.score * numberRoutes, [numberRoutes])
const increaseRoute = () => {
setNumberRoutes(numberRoutes + 1)
}
const decreaseRoute = () => {
numberRoutes > 0 && setNumberRoutes(numberRoutes - 1)
}
const handleChange = (e) => {
let newValue = parseInt(e.target.value)
if (isNaN(newValue)) {
setNumberRoutes(0)
} else {
setNumberRoutes(parseInt(e.target.value))
}
}
return (
<tr>
<th>
<h3>{props.length}</h3>
</th>
<th>
<div className="input-group" role="group" aria-label="Basic example">
<button type="button" className="btn btn-primary" onClick={increaseRoute}>+</button>
<input type="text" className="form-control text-center" style={{ width: '50px' }} value={numberRoutes} onChange={handleChange} />
<button type="button" className="btn btn-primary" onClick={decreaseRoute}>-</button>
</div>
</th>
<th>
<h3>{score}</h3>
</th>
</tr>
)
}
如何计算每个子组件的分数总和?
【问题讨论】:
标签: reactjs react-functional-component