父组件可以访问子组件的值,但无法对每个子组件的值求和。总数显示 0,而不是正确的总数。
我希望每个子组件的值的正确总和显示在总计中。父组件和子组件如下。
父组件
import { useState } from "react"
import SingleEntry from "./SingleEntry"
const TaxSource = ({ type }) => {
const [valuesFromSingleEntries, setValuesFromSingleEntries] = useState([])
const sendDataToTaxSource = (value, index) => {
const newValues = [...valuesFromSingleEntries]
newValues[index] = value
setValuesFromSingleEntries(newValues)
}
console.log(valuesFromSingleEntries)
const total = valuesFromSingleEntries.reduce((a, b) => a + b, 0)
return (
<>
<h3>{type}</h3>
<label
htmlFor='income'
className='block text-sm font-medium leading-6 text-gray-900 mt-6'
>
Income: {type}
</label>
{Array.from({ length: 5 }, (_, i) => (
<SingleEntry key={i} sendDataToTaxSource={sendDataToTaxSource} />
))}
<p>Total: {total}</p>
</>
)
}
export default TaxSource
子组件
import { useState } from "react"
const SingleEntry = ({ sendDataToTaxSource, index }) => {
const [value, setValue] = useState(0)
const handleValueChange = (e) => {
setValue(e.target.value)
}
const handleBlur = (e) => {
let inputValue = e.target.value
if (!isNaN(inputValue)) {
setValue(parseFloat(inputValue).toFixed(2))
}
sendDataToTaxSource(value, index)
}
return (
<>
<div className='sm:col-span-4'>
<div className='flex mb-2 sm:w-128'>
<div className='flex flex-col mr-2 w-3/4'>
<input
type='text'
name='description'
id='description'
placeholder='Enter description'
className='border-2 rounded-sm px-3 my-[-3px] border-gray-300 focus:outline-none focus:ring-1 focus:ring-indigo-600 focus:border-transparent'
/>
</div>
<div className='flex flex-col ml-2 w-1/4'>
<input
type='number'
step='0.01'
name='value'
id='value'
value={value}
onChange={handleValueChange}
onBlur={handleBlur}
placeholder='Enter value'
className='border-2 rounded-sm pr-3 my-[-3px] border-gray-300 focus:outline-none focus:ring-1 focus:ring-indigo-600 focus:border-transparent text-right'
/>
</div>
</div>
</div>
</>
)
}
export default SingleEntry
您没有将
index
传递给 SingleEntry
,因此它将无法更新数组中的正确位置。更新后的代码应该是:
{Array.from({ length: 5 }, (_, i) => (
<SingleEntry key={i} sendDataToTaxSource={sendDataToTaxSource} index={i} />
))}
我已复制您的代码以在codesandbox中进行测试,添加
index
后,它现在可以工作了:
https://codesandbox.io/p/sandbox/get-sum-kqxtcq?file=%2Fsrc%2FApp.js%3A65%2C22
我猜问题是因为
SingleEntry
需要一个 index
属性,而你没有从父级传递该属性。