react组件通信方式

1. 父组件向子组件通信

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const message = 'Hello from parent!';

  return (
    <div>
      <ChildComponent message={message} />
    </div>
  );
}

export default ParentComponent;

// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <p>{props.message}</p>
    </div>
  );
}

export default ChildComponent;

2. 子组件向父组件通信

// ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const [message, setMessage] = useState('');

  const handleMessage = (msg) => {
    setMessage(msg);
  };

  return (
    <div>
      <ChildComponent onMessage={handleMessage} />
      <p>Message from child: {message}</p>
    </div>
  );
}

export default ParentComponent;

// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
  const sendMessage = () => {
    props.onMessage('Hello from child!');
  };

  return (
    <button onClick={sendMessage}>Send Message</button>
  );
}

export default ChildComponent;

3. 跨级组件通信

// App.js
import React, { createContext, useContext } from 'react';
import GrandParentComponent from './GrandParentComponent';

const MessageContext = createContext();

function App() {
  return (
    <MessageContext.Provider value={'Hello from App!'}>
      <GrandParentComponent />
    </MessageContext.Provider>
  );
}

export default App;

// GrandParentComponent.js
import React from 'react';
import ParentComponent from './ParentComponent';

function GrandParentComponent() {
  return (
    <div>
      <ParentComponent />
    </div>
  );
}

export default GrandParentComponent;

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
import { MessageContext } from '../App';

function ParentComponent() {
  const message = useContext(MessageContext);
  return (
    <div>
      <ChildComponent message={message} />
    </div>
  );
}

export default ParentComponent;

// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <p>{props.message}</p>
    </div>
  );
}

export default ChildComponent;

4. 使用 Redux 进行全局状态管理

// store.js
import { createStore } from 'redux';

const initialState = {
  message: '',
};

function rootReducer(state = initialState, action) {
  switch (action.type) {
    case 'SET_MESSAGE':
      return { ...state, message: action.payload };
    default:
      return state;
  }
}

const store = createStore(rootReducer);

export default store;

// App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import ComponentA from './ComponentA';

function App() {
  return (
    <Provider store={store}>
      <ComponentA />
    </Provider>
  );
}

export default App;

// ComponentA.js
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';

function ComponentA() {
  const message = useSelector(state => state.message);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch({ type: 'SET_MESSAGE', payload: 'Hello from ComponentA!' });
  }, []);

  return (
    <div>
      <p>{message}</p>
    </div>
  );
}

export default ComponentA;

// ComponentB.js
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';

function ComponentB() {
  const message = useSelector(state => state.message);

  return (
    <div>
      <p>{message}</p>
    </div>
  );
}

export default ComponentB;

5. 使用 Refs 进行组件间通信

// ParentComponent.js
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const childRef = useRef(null);

  const triggerMethod = () => {
    childRef.current.childMethod();
  };

  return (
    <div>
      <button onClick={triggerMethod}>Trigger Child Method</button>
      <ChildComponent ref={childRef} />
    </div>
  );
}

export default ParentComponent;

// ChildComponent.js
import React from 'react';

class ChildComponent extends React.Component {
  childMethod = () => {
    console.log('Called from ParentComponent');
  };

  render() {
    return <div>Child Component</div>;
  }
}

export default ChildComponent;

6. 使用 Event Emitters 进行组件间通信

// EventEmitter.js
import Emitter from 'tiny-emitter/instance';

const eventEmitter = new Emitter();

export default eventEmitter;

// ComponentC.js
import React, { useEffect } from 'react';
import eventEmitter from './EventEmitter';

function ComponentC() {
  useEffect(() => {
    const handleEvent = (data) => {
      console.log('Received data:', data);
    };

    eventEmitter.on('my-event', handleEvent);

    return () => {
      eventEmitter.off('my-event', handleEvent);
    };
  }, []);

  return <div>Component C</div>;
}

export default ComponentC;

// ComponentD.js
import React, { useEffect } from 'react';
import eventEmitter from './EventEmitter';

function ComponentD() {
  useEffect(() => {
    eventEmitter.emit('my-event', 'Hello from ComponentD!');
  }, []);

  return <div>Component D</div>;
}

export default ComponentD;
相关推荐
高山我梦口香糖37 分钟前
[react]searchParams转普通对象
开发语言·前端·javascript
m0_7482352440 分钟前
前端实现获取后端返回的文件流并下载
前端·状态模式
m0_748240252 小时前
前端如何检测用户登录状态是否过期
前端
black^sugar2 小时前
纯前端实现更新检测
开发语言·前端·javascript
寻找沙漠的人2 小时前
前端知识补充—CSS
前端·css
GISer_Jing2 小时前
2025前端面试热门题目——计算机网络篇
前端·计算机网络·面试
m0_748245522 小时前
吉利前端、AI面试
前端·面试·职场和发展
理想不理想v3 小时前
webpack最基础的配置
前端·webpack·node.js
pubuzhixing3 小时前
开源白板新方案:Plait 同时支持 Angular 和 React 啦!
前端·开源·github
2401_857600953 小时前
SSM 与 Vue 共筑电脑测评系统:精准洞察电脑世界
前端·javascript·vue.js