vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > react组件通信

react里组件通信的几种方式小结

作者:剑九 六千里

本文主要介绍了react里组件通信的几种方式小结,包含了5种方式,主要是props传递,回调函数作为props,Context,Redux或MobX,refs,具有一定的参考价值,感兴趣的可以了解一下

1. props传递(父向子通信):

// 父组件
import ChildProps from "./ChildProps";
function ParentProps() {
    const message = "我是父组件";
    return <ChildProps message={message} />;
}

export default ParentProps;


// 子组件
function ChildProps(props: any) {
    return (<div>
        <span>{props.message}</span>
        <br />
        <span>我是子组件</span>
    </div>);
}

export default ChildProps;

在这里插入图片描述

2. 回调函数作为props(子向父通信):

// 父组件
import ChildrenEmit from "./ChildrenEmit";
function ParentEmit() {
    const handleButtonClick = (value: string) => {
        console.log(value, "ParentEmit: handleButtonClick");
    };
    return (
        <div>
            <ChildrenEmit onButtonClick={handleButtonClick}></ChildrenEmit>
        </div>
    );
}

export default ParentEmit;


// 子组件
function ChildrenEmit (props: { onButtonClick: (arg0: string) => void; }) {
    return (
        <button onClick={() => props.onButtonClick('按钮被点击了~')}>
            点击
        </button>
    )
}

export default ChildrenEmit;

在这里插入图片描述

3. Context API:

// MyContext.ts
// 创建Context
import { createContext } from "react";

export const MyContext = createContext('red');
// ParentContext.tsx
// 父组件
import { useContext } from "react";
import { MyContext } from "./MyContext";
import ChildrenContext from "./ChildrenContext";

const ParentContext = () => {
    const contextValue = useContext(MyContext);

    return (
        <MyContext.Provider value={contextValue}>
            <ChildrenContext />
        </MyContext.Provider>
    );
};

export default ParentContext;

// ChildrenContext.tsx
// 子组件
import { useContext } from "react";
import { MyContext } from "./MyContext";
import GrandsonContext from "./GrandsonContext";

const ChildrenContext = () => {
    const contentValue = useContext(MyContext);

    return (
        <div>
            <div>子组件颜色: {contentValue}</div>
            <GrandsonContext></GrandsonContext>
        </div>
    );
};
export default ChildrenContext;

// GrandsonContext.tsx
// 孙组件
import { useContext } from "react";
import { MyContext } from "./MyContext";
import GranddaughterContext from "./GranddaughterContext";

const GrandsonContext = () => {
    const contentValue = useContext(MyContext);

    return (
        <div>
            <div>孙组件1颜色: {contentValue}</div>
            <GranddaughterContext></GranddaughterContext>
        </div>
    );
};

export default GrandsonContext;

// GranddaughterContext.tsx
// 孙组件
import { useContext } from "react";
import { MyContext } from "./MyContext";

const GranddaughterContext = () => {
    const contentValue = useContext(MyContext);
    return (
        <div>
            <div>孙组件2颜色:{contentValue}</div>
        </div>
    );
};

export default GranddaughterContext;

在这里插入图片描述

4. Redux或MobX等状态管理库:

4.1 Redux使用示例

这个例子展示了如何创建一个简单的计数器应用,通过Redux管理状态。用户点击加减按钮时,会触发actions,然后通过reducer更新state,最终React组件根据新的state重新渲染。

npm install redux react-redux
// actions.ts
export const increment = () => {
    return { type: 'INCREMENT' };
  };
  
  export const decrement = () => {
    return { type: 'DECREMENT' };
  };
// reducer.ts
const initialState = { count: 0 };

function counterReducer(state = initialState, action: { type: any; }) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

export default counterReducer;
// store.ts
import { createStore } from 'redux';
import counterReducer from './reducer';

const store = createStore(counterReducer);

export default store;
import { connect } from 'react-redux';
import { increment, decrement } from './actions';
import { ReactElement, JSXElementConstructor, ReactNode, ReactPortal, MouseEventHandler } from 'react';

function ParentRedux(props: { count: string | number | boolean | ReactElement<any, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | null | undefined; onIncrement: MouseEventHandler<HTMLButtonElement> | undefined; onDecrement: MouseEventHandler<HTMLButtonElement> | undefined; }) {
  return (
    <div>
      <h1>Counter: {props.count}</h1>
      <button onClick={props.onIncrement}>+</button>
      <button onClick={props.onDecrement}>-</button>
    </div>
  );
}

const mapStateToProps = (state: { count: any; }) => ({
  count: state.count,
});

const mapDispatchToProps = (dispatch: (arg0: { type: string; }) => any) => ({
  onIncrement: () => dispatch(increment()),
  onDecrement: () => dispatch(decrement()),
});

export default connect(mapStateToProps, mapDispatchToProps)(ParentRedux);
import React from "react";
import "./App.css";
import { Provider } from 'react-redux';
import store from './page/redux/store';
import ParentProps from "./page/props/ParentProps";
import ParentEmit from "./page/emit/ParentEmit";
import ParentContext from "./page/context/ParentContext";
import ParentRefs from "./page/refs/ParentRefs";
import ParentRedux from "./page/redux/ParentRedux";

function App() {
    return (
        <div className="App">
            <div className="App-item">
                测试父子传参:<ParentProps></ParentProps>
            </div>
            <div className="App-item">
                测试子传父:<ParentEmit></ParentEmit>
            </div>
            <div className="App-item">
                测试context传参:<ParentContext></ParentContext>
            </div>
            <div className="App-item">
                测试refs传参:<ParentRefs></ParentRefs>
            </div>
            <Provider store={store}>
                <div className="App-item">
                    测试redux传参:<ParentRedux></ParentRedux>
                </div>
            </Provider>
        </div>
    );
}

export default App;

在这里插入图片描述

这个例子展示了如何创建一个简单的计数器应用,通过Redux管理状态。用户点击加减按钮时,会触发actions,然后通过reducer更新state,最终React组件根据新的state重新渲染。

5. refs:

// ParentRefs.tsx
// 父组件
import { useRef } from "react";
import ChildRefs from "./ChildRefs";

const ParentRefs = () => {
    const childRef = useRef<HTMLInputElement>(null);

    const handleClick = (): void => {
        childRef?.current?.focus();
    };

    return (
        <>
            <ChildRefs ref={childRef} />
            <button onClick={handleClick}>Focus Child Input</button>
        </>
    );
};

export default ParentRefs;
// ChildRefs.tsx
// 子组件
import { forwardRef } from 'react';

const ChildRefs = forwardRef<HTMLInputElement>((props, ref) => {
    return (
        <div>
            <input type="text" ref={ref} />
        </div>
    );
});

export default ChildRefs;

到此这篇关于react里组件通信的几种方式小结的文章就介绍到这了,更多相关react组件通信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文