react子组件之间如何联动
子组件通过父组件传递状态
子组件之间的联动通常通过父组件作为中介实现。父组件维护共享状态(如通过useState),并将状态和状态更新函数通过props传递给子组件。子组件通过调用父组件传递的函数来更新状态,触发其他子组件的重新渲染。
// 父组件
const Parent = () => {
const [sharedState, setSharedState] = React.useState('');
return (
<>
<ChildA value={sharedState} onChange={setSharedState} />
<ChildB value={sharedState} />
</>
);
};
// 子组件A(修改状态)
const ChildA = ({ value, onChange }) => (
<input value={value} onChange={(e) => onChange(e.target.value)} />
);
// 子组件B(显示状态)
const ChildB = ({ value }) => <div>{value}</div>;
使用Context API共享状态
当组件层级较深时,可通过React.createContext创建上下文,避免逐层传递props。父组件提供上下文值,子组件通过useContext钩子直接访问共享状态或更新函数。

const SharedContext = React.createContext();
// 父组件提供上下文
const Parent = () => {
const [state, setState] = React.useState('');
return (
<SharedContext.Provider value={{ state, setState }}>
<ChildA />
<ChildB />
</SharedContext.Provider>
);
};
// 子组件A(修改状态)
const ChildA = () => {
const { setState } = React.useContext(SharedContext);
return <input onChange={(e) => setState(e.target.value)} />;
};
// 子组件B(显示状态)
const ChildB = () => {
const { state } = React.useContext(SharedContext);
return <div>{state}</div>;
};
使用状态管理库(如Redux)
对于复杂应用,可使用Redux等状态管理工具。所有组件通过useSelector获取状态,通过useDispatch派发动作来更新全局状态,实现跨组件通信。

// 配置Redux Store略
// 子组件A(派发动作)
const ChildA = () => {
const dispatch = useDispatch();
return (
<input onChange={(e) => dispatch(updateStateAction(e.target.value))} />
);
};
// 子组件B(获取状态)
const ChildB = () => {
const state = useSelector((state) => state.value);
return <div>{state}</div>;
};
使用自定义事件或发布订阅模式
通过事件总线(如EventEmitter)实现组件间直接通信。子组件A触发事件,子组件B监听事件并响应。适用于非父子关系的组件。
const eventBus = new EventEmitter();
// 子组件A(触发事件)
const ChildA = () => (
<button onClick={() => eventBus.emit('event', 'data')}>触发</button>
);
// 子组件B(监听事件)
const ChildB = () => {
const [data, setData] = React.useState('');
React.useEffect(() => {
eventBus.on('event', setData);
return () => eventBus.off('event', setData);
}, []);
return <div>{data}</div>;
};
使用Refs暴露子组件方法
通过useImperativeHandle和forwardRef暴露子组件方法,父组件通过ref调用子组件函数,间接触发其他子组件更新。
// 子组件A(暴露方法)
const ChildA = React.forwardRef((props, ref) => {
const [value, setValue] = React.useState('');
React.useImperativeHandle(ref, () => ({
getValue: () => value,
}));
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
});
// 父组件
const Parent = () => {
const childARef = React.useRef();
const handleClick = () => {
alert(childARef.current.getValue());
};
return (
<>
<ChildA ref={childARef} />
<button onClick={handleClick}>获取值</button>
</>
);
};






