react組件通信

需要組件通信的幾種情況:
1.父組件向子組件通信
2.子組件向父組件通信
3.跨級組件通信
4.沒有嵌套關(guān)系組件之間的通信


1.父組件向子組件通信
React數(shù)據(jù)流動是單向的,父組件向子組件通信也是最常見的;父組件通過props向子組件傳遞需要的信息
示例:

//子組件:
import React from 'react';
import PropTypes from 'prop-types';

export default function Child({ name }) {
    return <h1>Hello, {name}</h1>;
}

Child.propTypes = {
    name: PropTypes.string.isRequired,
};
//父組件:
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
    render() {
        return (
            <div>
                <Child name="Sara" />
            </div>
        );
    }
}

export default Parent;

2.子組件向父組件通信
示例:

//子組件:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class List3 extends Component {
    static propTypes = {
        hideConponent: PropTypes.func.isRequired,
    }
    render() {
        return (
            <div>
                我是List3
                <button onClick={this.props.hideConponent}>隱藏List3組件</button>
            </div>
        );
    }
}

export default List3;
//父組件
import React, { Component } from 'react';
import List3 from './components/List3';
export default class App extends Component {
    constructor(...args) {
        super(...args);
        this.state = {
            isShowList3: false,
        };
    }
    showConponent = () => {
        this.setState({
            isShowList3: true,
        });
    }
    hideConponent = () => {
        this.setState({
            isShowList3: false,
        });
    }
    render() {
        return (
            <div>
                <button onClick={this.showConponent}>顯示Lists組件</button>
                {
                    this.state.isShowList3 ?
                        <List3 hideConponent={this.hideConponent} />
                    :
                    null
                }

            </div>
        );
    }
}

3.跨級組件通信
(1)層層組件傳遞props
例如A組件和B組件之間要進(jìn)行通信,先找到A和B公共的父組件,A先向C組件通信,C組件通過props和B組件通信,此時C組件起的就是中間件的作用
(2)使用context
context是一個全局變量,像是一個大容器,在任何地方都可以訪問到,我們可以把要通信的信息放在context上,然后在其他組件中可以隨意取到;
但是React官方不建議使用大量context,盡管他可以減少逐層傳遞,但是當(dāng)組件結(jié)構(gòu)復(fù)雜的時候,我們并不知道context是從哪里傳過來的;而且context是一個全局變量,全局變量正是導(dǎo)致應(yīng)用走向混亂的罪魁禍?zhǔn)?
示例:

//子組件:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class ListItem extends Component {
    // 子組件聲明自己要使用context
    static contextTypes = {
        color: PropTypes.string,
    }
    static propTypes = {
        value: PropTypes.string,
    }
    render() {
        const { value } = this.props;
        return (
            <li style={{ background: this.context.color }}>
                <span>{value}</span>
            </li>
        );
    }
}

export default ListItem;
//父組件
import ListItem from './ListItem';

class List extends Component {
    // 父組件聲明自己支持context
    static childContextTypes = {
        color: PropTypes.string,
    }
    static propTypes = {
        list: PropTypes.array,
    }
    // 提供一個函數(shù),用來返回相應(yīng)的context對象
    getChildContext() {
        return {
            color: 'red',
        };
    }
    render() {
        const { list } = this.props;
        return (
            <div>
                <ul>
                    {
                        list.map((entry, index) =>
                            <ListItem key={`list-${index}`} value={entry.text} />,
                       )
                    }
                </ul>
            </div>
        );
    }
}

export default List;
import React, { Component } from 'react';
import List from './components/List';

const list = [
    {
        text: '題目一',
    },
    {
        text: '題目二',
    },
];
export default class App extends Component {
    render() {
        return (
            <div>
                <List
                    list={list}
                />
            </div>
        );
    }
}

  1. 沒有嵌套關(guān)系的組件通信
    使用自定義事件的方式
    下面例子中的組件關(guān)系: List1和List2沒有任何嵌套關(guān)系,App是他們的父組件;
    實(shí)現(xiàn)這樣一個功能: 點(diǎn)擊List2中的一個按鈕,改變List1中的信息顯示
    首先需要項目中安裝events 包:
npm install events --save

在src下新建一個util目錄里面建一個events.js

import { EventEmitter } from 'events';
export default new EventEmitter();

list1:

import React, { Component } from 'react';
import emitter from '../util/events';

class List extends Component {
    constructor(props) {
        super(props);
        this.state = {
            message: 'List1',
        };
    }
    componentDidMount() {
        // 組件裝載完成以后聲明一個自定義事件
        this.eventEmitter = emitter.addListener('changeMessage', (message) => {
            this.setState({
                message,
            });
        });
    }
    componentWillUnmount() {
        emitter.removeListener(this.eventEmitter);
    }
    render() {
        return (
            <div>
                {this.state.message}
            </div>
        );
    }
}

export default List;

list2:

import React, { Component } from 'react';
import emitter from '../util/events';

class List2 extends Component {
    handleClick = (message) => {
        emitter.emit('changeMessage', message);
    };
    render() {
        return (
            <div>
                <button onClick={this.handleClick.bind(this, 'List2')}>點(diǎn)擊我改變List1組件中顯示信息</button>
            </div>
        );
    }
}

APP:

import React, { Component } from 'react';
import List1 from './components/List1';
import List2 from './components/List2';
export default class App extends Component {
    render() {
        return (
            <div>
                <List1 />
                <List2 />
            </div>
        );
    }
}

自定義事件是典型的發(fā)布訂閱模式,通過向事件對象上添加監(jiān)聽器和觸發(fā)事件來實(shí)現(xiàn)組件之間的通信


當(dāng)業(yè)務(wù)邏輯復(fù)雜到一定程度,就可以考慮引入redux等狀態(tài)管理工具

本人學(xué)識有限 文章多有不足

若有錯誤 請大方指出 以免誤導(dǎo)他人

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • react是以組合組件的形式組織的,那么組件間是如何傳遞信息的呢? 父組件向子組件通信 parent組件傳給chi...
    DCbryant閱讀 563評論 0 0
  • 1 組件間通信 父組件向子組件通信React規(guī)定了明確的單向數(shù)據(jù)流,利用props將數(shù)據(jù)從父組件傳遞給子組件。故我...
    Dabao123閱讀 1,005評論 0 4
  • react組件通信是一個常用功能,在做react項目中經(jīng)常遇到 React組件層級關(guān)系 在了解Reat組件通訊之前...
    ZhangYu31閱讀 522評論 3 16
  • 在現(xiàn)代的三大框架中,其中兩個Vue和React框架,組件間傳值方式有哪些? 組件間的傳值方式 組件的傳值場景無外乎...
    mdiep閱讀 1,348評論 0 0
  • 摩爾根作為遺傳學(xué)的第二號人物,他在孟德爾的基礎(chǔ)上通過假說演繹法把基因定位在了染色體上,而且還研究出了遺傳學(xué)第二大定...
    子非魚lily閱讀 925評論 0 0

友情鏈接更多精彩內(nèi)容