react兄弟节点如何通讯
兄弟组件通信方法
在React中,兄弟组件之间的通信可以通过以下几种方式实现:
状态提升(Lifting State Up)
将共享状态提升到最近的共同父组件中,通过props向下传递数据和回调函数。
function Parent() {
const [sharedState, setSharedState] = useState('');
return (
<>
<ChildA value={sharedState} onChange={setSharedState} />
<ChildB value={sharedState} />
</>
);
}
function ChildA({ value, onChange }) {
return <input value={value} onChange={(e) => onChange(e.target.value)} />;
}
function ChildB({ value }) {
return <div>{value}</div>;
}
使用Context API
创建上下文提供共享状态,兄弟组件通过useContext hook访问。
const MyContext = createContext();
function Parent() {
const [value, setValue] = useState('');
return (
<MyContext.Provider value={{ value, setValue }}>
<ChildA />
<ChildB />
</MyContext.Provider>
);
}
function ChildA() {
const { setValue } = useContext(MyContext);
return <input onChange={(e) => setValue(e.target.value)} />;
}
function ChildB() {
const { value } = useContext(MyContext);
return <div>{value}</div>;
}
使用状态管理库
Redux、MobX等状态管理库可以集中管理应用状态,兄弟组件通过连接store获取和更新状态。
// Redux示例
import { useSelector, useDispatch } from 'react-redux';
function ChildA() {
const dispatch = useDispatch();
return <input onChange={(e) => dispatch(updateValue(e.target.value))} />;
}
function ChildB() {
const value = useSelector((state) => state.value);
return <div>{value}</div>;
}
使用自定义事件
通过事件发射器或自定义事件系统实现组件间通信。
const eventEmitter = new EventEmitter();
function ChildA() {
return <input onChange={(e) => eventEmitter.emit('update', e.target.value)} />;
}
function ChildB() {
const [value, setValue] = useState('');
useEffect(() => {
const listener = (val) => setValue(val);
eventEmitter.on('update', listener);
return () => eventEmitter.off('update', listener);
}, []);
return <div>{value}</div>;
}
使用ref和forwardRef
父组件通过ref访问子组件实例,间接实现兄弟组件通信。
const ChildA = forwardRef((props, ref) => {
return <input ref={ref} />;
});
function Parent() {
const inputRef = useRef();
const [value, setValue] = useState('');
return (
<>
<ChildA ref={inputRef} />
<button onClick={() => setValue(inputRef.current.value)}>Update</button>
<ChildB value={value} />
</>
);
}
选择哪种方法取决于应用复杂度、组件层级深度和性能要求。简单场景推荐状态提升,复杂应用考虑使用Context或状态管理库。







