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;
相关推荐
清灵xmf13 分钟前
TypeScript 类型进阶指南
javascript·typescript·泛型·t·infer
小白学大数据20 分钟前
JavaScript重定向对网络爬虫的影响及处理
开发语言·javascript·数据库·爬虫
qq_3901617728 分钟前
防抖函数--应用场景及示例
前端·javascript
334554321 小时前
element动态表头合并表格
开发语言·javascript·ecmascript
John.liu_Test1 小时前
js下载excel示例demo
前端·javascript·excel
Yaml41 小时前
智能化健身房管理:Spring Boot与Vue的创新解决方案
前端·spring boot·后端·mysql·vue·健身房管理
PleaSure乐事1 小时前
【React.js】AntDesignPro左侧菜单栏栏目名称不显示的解决方案
前端·javascript·react.js·前端框架·webstorm·antdesignpro
哟哟耶耶1 小时前
js-将JavaScript对象或值转换为JSON字符串 JSON.stringify(this.SelectDataListCourse)
前端·javascript·json
getaxiosluo1 小时前
react jsx基本语法,脚手架,父子传参,refs等详解
前端·vue.js·react.js·前端框架·hook·jsx
理想不理想v1 小时前
vue种ref跟reactive的区别?
前端·javascript·vue.js·webpack·前端框架·node.js·ecmascript