欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

react里組件通信的幾種方式小結(jié)

 更新時間:2024年06月18日 08:54:51   作者:劍九 六千里  
本文主要介紹了react里組件通信的幾種方式小結(jié),包含了5種方式,主要是props傳遞,回調(diào)函數(shù)作為props,Context,Redux或MobX,refs,具有一定的參考價值,感興趣的可以了解一下

1. props傳遞(父向子通信):

  • 說明: 父組件通過props屬性向子組件傳遞數(shù)據(jù)。
  • 如何進行: 在父組件中定義子組件時,通過屬性名將值傳給子組件,子組件通過this.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. 回調(diào)函數(shù)作為props(子向父通信):

  • 說明: 子組件通過調(diào)用父組件傳遞的回調(diào)函數(shù),將信息傳回給父組件。
  • 如何進行: 父組件定義一個方法,將其作為prop傳遞給子組件;子組件在適當?shù)臅r候調(diào)用這個函數(shù),傳遞數(shù)據(jù)或事件信息。
// 父組件
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:

  • 說明: 方式:React提供了一個Context API,允許你在組件樹中傳遞數(shù)據(jù),而無需手動逐層傳遞props。
  • 如何使用:創(chuàng)建一個Context,使用React.createContext();在最頂層的組件中使用<MyContext.Provider value={value}>包裹需要共享狀態(tài)的組件樹;在消費組件中使用<MyContext.Consumer>useContext(MyContext)來訪問上下文中的值。
// MyContext.ts
// 創(chuàng)建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等狀態(tài)管理庫:

  • 方式:適用于大型應用,通過將狀態(tài)提升到一個單一的store中管理,任何組件都可以訪問和修改store中的狀態(tài)。
  • 如何使用:引入相應的庫并設置store,使用Provider組件將store包裹在應用的最外層,組件內(nèi)部通過connect函數(shù)(Redux)Observer(MobX)等與store連接,從而獲取或改變狀態(tài)。

4.1 Redux使用示例

這個例子展示了如何創(chuàng)建一個簡單的計數(shù)器應用,通過Redux管理狀態(tài)。用戶點擊加減按鈕時,會觸發(fā)actions,然后通過reducer更新state,最終React組件根據(jù)新的state重新渲染。

  • 安裝 redux 和 和 react-redux 庫。
npm install redux react-redux
  • 創(chuàng)建 Action
// actions.ts
export const increment = () => {
    return { type: 'INCREMENT' };
  };
  
  export const decrement = () => {
    return { type: 'DECREMENT' };
  };
  • 創(chuàng)建 reducer
// 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;
  • 創(chuàng)建 store
// store.ts
import { createStore } from 'redux';
import counterReducer from './reducer';

const store = createStore(counterReducer);

export default store;
  • 創(chuàng)建組件使用
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;

在這里插入圖片描述

這個例子展示了如何創(chuàng)建一個簡單的計數(shù)器應用,通過Redux管理狀態(tài)。用戶點擊加減按鈕時,會觸發(fā)actions,然后通過reducer更新state,最終React組件根據(jù)新的state重新渲染。

5. refs:

  • 方式:主要用于訪問DOM元素或在組件之間傳遞一個可變的引用。
  • 如何使用:可以通過React.createRef()創(chuàng)建ref,然后將其附加到特定的React元素上。在組件中,可以通過this.myRef.current訪問DOM元素或在類組件間傳遞ref以直接操作另一個組件的實例。
// 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;

到此這篇關(guān)于react里組件通信的幾種方式小結(jié)的文章就介紹到這了,更多相關(guān)react組件通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Vue中關(guān)于computed計算屬性的妙用

    Vue中關(guān)于computed計算屬性的妙用

    這篇文章主要介紹了Vue中關(guān)于computed計算屬性的妙用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Vue3?$emit用法指南(含選項API、組合API及?setup?語法糖)

    Vue3?$emit用法指南(含選項API、組合API及?setup?語法糖)

    這篇文章主要介紹了Vue3?$emit用法指南,使用?emit,我們可以觸發(fā)事件并將數(shù)據(jù)傳遞到組件的層次結(jié)構(gòu)中,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2022-07-07
  • vue實現(xiàn)購物車的小練習

    vue實現(xiàn)購物車的小練習

    這篇文章主要為大家詳細介紹了vue實現(xiàn)購物車的小練習,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-12-12
  • VUE實現(xiàn)一個Flappy Bird游戲的示例代碼

    VUE實現(xiàn)一個Flappy Bird游戲的示例代碼

    這篇文章主要介紹了VUE實現(xiàn)一個Flappy Bird的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • vue實現(xiàn)動態(tài)列表點擊各行換色的方法

    vue實現(xiàn)動態(tài)列表點擊各行換色的方法

    今天小編就為大家分享一篇vue實現(xiàn)動態(tài)列表點擊各行換色的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • vite前端構(gòu)建Turborepo高性能monorepo方案

    vite前端構(gòu)建Turborepo高性能monorepo方案

    這篇文章主要為大家介紹了vite前端構(gòu)建Turborepo高性能monorepo方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • vue集成高德地圖amap-jsapi-loader的實現(xiàn)

    vue集成高德地圖amap-jsapi-loader的實現(xiàn)

    本文主要介紹了vue集成高德地圖amap-jsapi-loader的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-06-06
  • 解決在vue項目中,發(fā)版之后,背景圖片報錯,路徑不對的問題

    解決在vue項目中,發(fā)版之后,背景圖片報錯,路徑不對的問題

    下面小編就為大家分享一篇解決在vue項目中,發(fā)版之后,背景圖片報錯,路徑不對的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • Vue組件通信之父傳子與子傳父詳細講解

    Vue組件通信之父傳子與子傳父詳細講解

    這篇文章主要介紹了React中父子組件通信詳解,在父組件中,為子組件添加屬性數(shù)據(jù),即可實現(xiàn)父組件向子組件通信,文章通過圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-10-10
  • Vue源碼探究之虛擬節(jié)點的實現(xiàn)

    Vue源碼探究之虛擬節(jié)點的實現(xiàn)

    這篇文章主要介紹了Vue源碼探究之虛擬節(jié)點的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-04-04

最新評論