构建一个react项目 - react的通信方式

49 阅读2分钟

props父子通信

import React, { useState } from 'react';
import ChildOne from './childOne';
​
const CommonVariable = () => {
    const [textChild, setTextChild] = useState('默认的内容');
​
    return(
        <>
            <div>我是父组件</div>
            <ChildOne textChild={textChild} />
        </>
    )
}
export default CommonVariable;
​
​
const ChildOne = (props) => {
    return (
        <>
            <h4>我是child one组件</h4>
            <span>{ props.textChild }</span>
        </>
    )
}
export default ChildOne;

回调函数,子父通信

import React, { useState } from 'react';
import ChildOne from './childOne';
​
const CommonVariable = () => {
    const [text, setText] = useState('这是展示在父组件的内容');
    const handleFunc = (val) => {
        setText(val)
    }
​
    return(
        <>
            <div>我是父组件</div>
            <span>{ text }</span>
            <ChildOne textChild={textChild} handleFunc={handleFunc}/>
        </>
    )
}
export default CommonVariable;
​
​
const ChildOne = (props) => {
    return (
        <>
            <h4>我是child one组件</h4>
            <span>{ props.textChild }</span>
            <button onClick={() => props.handleFunc('我是来自childOne的内容')}>点击改变父组件的默认文本</button>
        </>
    )
}
export default ChildOne;

变量提升,兄弟组件通信

import React, { useState } from 'react';
import ChildOne from './childOne';
import ChildTwo from './childTwo';
​
const CommonVariable = () => {
    const [textChild, setTextChild] = useState('默认的内容');
​
    const handleFunc = (val) => {
        setText(val)
    }
​
    return(
        <>
            <div>我是父组件</div>
​
            <ChildOne textChild={textChild}/>
            <ChildTwo setTextChild={setTextChild}/>
        </>
    )
}
export default CommonVariable;
​
​
const ChildOne = (props) => {
    return (
        <>
            <h4>我是child one组件</h4>
            <span>{ props.textChild }</span>
        </>
    )
}
export default ChildOne;
​
const ChildTwo = (props) => {
    return (
        <>
            <h4>我是child two组件</h4>
            <button onClick={() => props.setTextChild('我是来自childTwo的值')}>传值给childOne</button>
        </>
    )
}
export default ChildTwo;

Context, 跨组件通信

import React, { useState, createContext } from 'react';
import ChildThree from './childThree';
​
export const ObjContext = createContext();
​
const personInfo = {
    name: 'elio',
    age: 26,
    gender: 'man'
}
​
const addressInfo = {
    country: 'China',
    province: 'guangdong'
}
​
const CommonVariable = () => {
    const { Provider } = ObjContext;
    const [text, setText] = useState('这是展示在父组件的内容');
    const contextObj = {
        personInfo,
        addressInfo,
        text,
​
        setText,
    }
​
    return(
        <>
            <div>我是父组件</div>
            <span>{ text }</span>
​
            <Provider value={contextObj}>
                <ChildThree />
            </Provider>
        </>
    )
}
export default CommonVariable;
​
​
import { ObjContext } from './index'const ChildThree = (props) => {
    const { personInfo, addressInfo, text, setText } = useContext(ObjContext);
    const { name, age, gender } = personInfo;
    const { country, province } = addressInfo;
​
    return (
        <>
            <h4>我是child three组件 -  { text }</h4>
            <div> { name } - { age } - { gender } </div>
            <div> { country } - { province } </div>
            <button onClick={() => setText('改变你的值')}>改变父元素的text</button>
        </>
    )
}
export default ChildThree;

消息订阅/发布 (pubsub)

安装:npm install pubsub-js
​
引入:import PubSub from 'pubsub-js' 

实现

import React, { useState, useEffect, createContext } from 'react';
import PubSub from 'pubsub-js';
​
import ChildFour from './childFour';
​
const personInfo = {
    name: 'elio',
    age: 26,
    gender: 'man'
}
​
const addressInfo = {
    country: 'China',
    province: 'guangdong'
}
​
const CommonVariable = () => {
​
    useEffect(() => {
        /**
         * 消息发布
         * 消息名称:all-info
         * 消息内容 任意类型,此处发布了一个对象
         */
        PubSub.publish('all-info', {
            'person-info': personInfo,
            'address-info': addressInfo
        });
    }, [])
​
    return(
        <>
            <div>我是父组件</div>
            <span>{ text }</span>
​
            <ChildFour />
        </>
    )
}
export default CommonVariable;
​
​
import PubSub from 'pubsub-js';
const ChildFour = (props) => {
    useEffect(() => {
        /**
         * 消息订阅 
         * 消息名称:all-info 第二个参数是一个函数(消息名,消息数据)
         */
        PubSub.subscribe('all-info', (msg, data) => {
            console.log(' -- msg -- ', msg);
            console.log(' -- data -- ', data);
        });
    }, [])
​
    return (
        <>
            <h4>我是child four组件</h4>
        </>
    )
}
export default ChildFour;

Redux - 状态管理

单独学习