React函数组件如何通过子组件函数更新父组件state(寻求Hooks实现方案)
完全可以实现,实现逻辑和类组件的思路一致,核心是父组件将统一的状态更新方法通过props透传给子组件调用即可,以下是基于Hooks的完整实现:
父组件实现
import { useState } from 'react'; import ChildComponent from './ChildComponent'; function ParentComponent() { // 定义和类组件结构一致的状态 const [formState, setFormState] = useState({ name: '', email: '' }); // 封装统一的状态更新方法,逻辑和你提供的类组件setValues完全对齐 const setValues = (stateKey, value) => { setFormState(prev => ({ ...prev, [stateKey]: value })); }; return ( <ChildComponent name={formState.name} email={formState.email} setValues={setValues} /> ); } export default ParentComponent;
子组件实现
function ChildComponent(props) { return ( <> <input type="text" value={props.name} onChange={(e) => props.setValues('name', e.target.value)} /> <input type="email" value={props.email} onChange={(e) => props.setValues('email', e.target.value)} /> </> ); } export default ChildComponent;
如果存在子组件层级过深的场景,你也可以使用useContext来避免多层props透传,上述方案已经可以覆盖你的需求。
内容的提问来源于stack exchange,提问作者fourie_lean
相关产品推荐
相关产品推荐

