组件间的通信

时间:2021-07-20
本文章向大家介绍组件间的通信,主要包括组件间的通信使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

组件之间的通信

每个组件之间都是独立的,但是它们之间也存在关系,存在关系就需要通信;

组件之间的通信也会看组件之间是什么关系,这里先介绍只基于React父子组件之间的简单通信:

在React中父子组件通信是基于一个属性props,子组件会从父组件那里接收属性,函数等;

01-props传递属性

父组件

class Father extends Component {
    constructor(props) {
        super(props)

        this.state = {
            name: "张三",
            age: 19,
            height: 1.88,
        }
    }


    render() {
        return (
            <div>
                <Child name={this.state.name} age={this.state.age} height={this.state.height} />
            </div>
        )
    }
}

子组件

function Child(props) {
    const { name, age, height } = props;

    return (
        <div>
            <div>名字:{name} 年龄:{age} 身高:{height}</div>
        </div>
    )
}

我们只需要在使用组件的时候往‘里面’塞值就行了,但是有个注意点,有些属性是不归props管的,例如:ref,key等,这些属性是不会随着props向下传递的;

02-props传递函数

上面我们讲解了props传递属性,props传递函数是让父子组件相互之间响应的关键;

简单讲下业务逻辑:父组件有一个属性counter,这个属性会子组件里面的button点击而增加

父组件

 class App extends Component {
    constructor(props) {
        super(props)

        this.state = {
            counter: 0
        }
    }

    increment() {
        this.setState({
            counter: ++this.state.counter
        })
    }

    render() {
        return (
            <div>
                <p>{this.state.counter}</p>
                {/* 记住需要绑定this,其他的都和基本数据类型相同*/}
                <Child increment={e => this.increment()}></Child>
            </div>
        )
    }
}

子组件:

function Child(props) {
    const {increment} = props;

    return (
        <button onClick={increment}>+</button>
    );
}

注意一下this的绑定就行了

03-props传递时的类型检测

在react脚手架里面集成了prop-types这个模块;

直接引用就完事了

import PropType from "prop-types"
// 此时的Child组件是函数式组件
// 为Child的props进行类型检测
Child.propTypes = {
    // isRequired是将这个属性置为必须传入的
    name: PropType.string.isRequired,
    age: PropType.number,
    height: PropType.number,
    names: PropType.array,
};

// 为Child组件添加默认值,并且即使设置了isRequired也不会报警告
Child.defaultProps = {
    name: "lsq",
    age: 18,
    height: 1.84,
    names: ["小闯", "小猛", "小攀"],
};

类组件直接在类组件内部添加static

export default class App extends Component {
		...
		static propTypes = {...}
   	static defaultProps = {...}
		...
}

至于其他的组件通信,我们后面再讲
完整代码,请到git仓库找

原文地址:https://www.cnblogs.com/coderLsq/p/15037188.html