当前位置:首页 > React

react模型之间如何通信

2026-03-10 23:28:53React

React 组件间通信方法

父子组件通信(Props 传递)
父组件通过 props 向子组件传递数据或回调函数,子组件通过接收 props 实现数据更新或触发父组件逻辑。

// 父组件
function Parent() {
  const [data, setData] = useState("Hello");
  return <Child message={data} onUpdate={setData} />;
}

// 子组件
function Child({ message, onUpdate }) {
  return <button onClick={() => onUpdate("Updated")}>{message}</button>;
}

子父组件通信(回调函数)
子组件通过父组件传递的回调函数向上传递数据或事件,父组件通过函数处理子组件的操作。

兄弟组件通信(状态提升)
将共享状态提升至共同的父组件,通过 props 分发给兄弟组件,实现状态同步。

function Parent() {
  const [sharedState, setSharedState] = useState("");
  return (
    <>
      <SiblingA value={sharedState} />
      <SiblingB onChange={setSharedState} />
    </>
  );
}

跨层级组件通信

Context API
通过 React.createContext 创建上下文,Provider 提供数据,子组件通过 useContextConsumer 消费数据。

react模型之间如何通信

const MyContext = React.createContext();

function App() {
  return (
    <MyContext.Provider value="Global Data">
      <Component />
    </MyContext.Provider>
  );
}

function Component() {
  const value = useContext(MyContext);
  return <div>{value}</div>;
}

事件总线(Event Emitter)
使用第三方库(如 events)或自定义事件系统,实现组件间发布/订阅模式。

import EventEmitter from 'events';
const emitter = new EventEmitter();

// 发布事件
emitter.emit("event", data);

// 订阅事件
emitter.on("event", (data) => console.log(data));

全局状态管理

Redux
通过单一 store 管理状态,组件通过 useSelector 获取状态,通过 useDispatch 派发 action 更新状态。

react模型之间如何通信

import { configureStore, createSlice } from '@reduxjs/toolkit';

const slice = createSlice({
  name: 'data',
  initialState: { value: 0 },
  reducers: { increment: (state) => { state.value += 1; } }
});

const store = configureStore({ reducer: slice.reducer });

function Component() {
  const count = useSelector((state) => state.data.value);
  const dispatch = useDispatch();
  return <button onClick={() => dispatch(slice.actions.increment())}>{count}</button>;
}

MobX
通过 observable 状态和 reactions 实现响应式更新,组件通过 observer 包裹自动响应状态变化。

import { observer } from 'mobx-react-lite';
import { makeAutoObservable } from 'mobx';

class Store {
  count = 0;
  constructor() { makeAutoObservable(this); }
  increment() { this.count += 1; }
}

const store = new Store();

const Component = observer(() => (
  <button onClick={() => store.increment()}>{store.count}</button>
));

其他通信方式

Ref 转发(ForwardRef)
父组件通过 forwardRef 获取子组件实例,直接调用子组件方法或访问 DOM。

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    method: () => console.log("Child method called")
  }));
  return <div>Child</div>;
});

function Parent() {
  const childRef = useRef();
  return <Child ref={childRef} onClick={() => childRef.current.method()} />;
}

状态管理库(Zustand/Jotai)
轻量级状态管理方案,例如 Zustand 通过 create 创建 store,组件直接使用 hook 获取状态。

import create from 'zustand';

const useStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 }))
}));

function Component() {
  const { count, increment } = useStore();
  return <button onClick={increment}>{count}</button>;
}

标签: 模型通信
分享给朋友:

相关文章

vue实现串口通信

vue实现串口通信

Vue 实现串口通信的方法 在 Vue 项目中实现串口通信,通常需要借助浏览器提供的 Web Serial API 或第三方库。以下是几种常见的实现方式: 使用 Web Serial API…

react如何通信

react如何通信

React 组件通信方式 React 组件间的通信方式多样,具体选择取决于组件关系和场景需求。以下是常见方法: 父子组件通信 父组件通过 props 向子组件传递数据,子组件通过回调函数通知父组件…

使用vue实例实现通信

使用vue实例实现通信

Vue 实例通信方法 父子组件通信 使用 props 传递数据给子组件,子组件通过 $emit 触发事件传递数据给父组件。 父组件: <template> <ChildCo…

react组件之间是如何通信

react组件之间是如何通信

父子组件通信(Props) 父组件通过props向子组件传递数据或方法,子组件通过接收props实现数据或行为的更新。父组件定义props,子组件通过this.props(类组件)或直接解构(函数组件…

react如何完成组件通信

react如何完成组件通信

父子组件通信 父组件通过props向子组件传递数据。子组件通过调用父组件传递的回调函数与父组件通信。 // 父组件 function Parent() { const [data, setDat…

css制作模型

css制作模型

使用CSS制作3D模型 CSS可以通过transform属性实现简单的3D效果,结合perspective和transform-style属性可以创建基础的3D模型。 基本3D立方体示例: <…