在 react 中,无需为每个子组件单独声明状态变量;可通过数组或对象统一管理子组件状态,并由父组件提供带索引/id参数的更新函数实现精准控制。
在构建动态子组件列表(如循环渲染多个
import { useState } from 'react';
const Child = ({ color, updateColor }) => {
const handleClick = () => updateColor('red'); // 触发父级更新逻辑
return (
);
};
export default function Parent() {
// ✅ 单一状态:用数组存储所有子组件的颜色
const [colors, setColors] = useState(['yellow', 'yellow', 'yellow']);
// ✅ 通用更新函数:接收 index 和新值,安全更新指定位置
const updateColor = (index, newColor) => {
setColors(prev =>
prev.map((color, i) => i === index ? newColor : color)
);
};
return (
<>
Parent
{/* ✅ 静态渲染示例 */}
updateColor(0, c)}
/>
updateColor(1, c)}
/>
updateColor(2, c)}
/>
{/* ✅ 推荐:动态渲染(支持任意数量子组件) */}
{/* {colors.map((color, index) => (
updateColor(index, c)}
/>
))} */}
>
);
}
w') × n,显著提升可维护性;该模式兼顾简洁性、可扩展性与 React 最佳实践,是管理批量子组件状态的工业级解决方案。