❤React-React 组件通讯

❤ React 组件通讯

组件通讯将教我们的内容:

  • 能够使用道具接收数据W
  • 能够实现父子组件之间的通讯
  • 能够实现兄弟组件之间的通讯
  • 能够给组件添加道具校验
  • 能够说出生命周期常用的钩子函数
  • 能够知道高阶组件的作用

1、 组件通讯介绍

组件是独立且封闭的单元,默认情况下,只能使用组件自己的数据。

在组件化过程中,我们将一个完整的功能拆分成多个组件,以更好的完成整个应用的功能。而在这个过程中,多个组件之间不可避免的要共享某些数据为了实现这些功能,就需要打破组件的独立封闭性,让其与外界沟通。这个过程就是组件通讯。

换个意思说就是,大家之间总是需要沟通的呗

2、 组件的props

组件是封闭的,要接收外部数据应该通过 props 来实现props的作用:接收传递给组件的数据传递数据:给组件标签添加属性 接收数据:函数组件通过参数props接收数据,类组件通过this.props接收数据

类组件和函数式组件传递参数进行通讯如下图所示:(推荐函数式组件)

函数组件props

类组件this.props

组件props三个特点:

① 可以给组件传递任意类型的数据 ② props是只读的对象,只能读取属性的值,无法修改对象 ③ 注意:使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取props

3、 组件通讯的三种方式

父子、子父、兄弟组件

(1)传递方式1

(2)传递方式2

案例

javascript

 代码解读
复制代码import React from 'react';
import ReactDOM from 'react-dom/client'; //React 18 
import './index.css'
class Parent extends React.Component{
    state={
        lastName:'父亲',
    }
    getChildMsg=(msg)=>{
        console.log('接收到子组件数据',msg);  
        this.setState({
            lastName:msg
        })
    }
    render(){
        return (
        <div className='parent'>
             父组件:
             {this.state.lastName}
             <Child getMsg={this.getChildMsg}></Child>
        </div>)
    }
}
class Child extends React.Component{
    state={
        msg:'行为'
    }
    handleClick=()=>{
        this.props.getMsg(this.state.msg);
    }
    render(){
        return (
            <div className='child'>
              子组件:<button onClick={this.handleClick}> 传递数据给付组件</button>
            </div>) 
    }
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Parent name='jack' age={18} colors={['red','green','blue']} 
fn={()=>{console.log('这是一个组件传递函数')}} tag={<p>设置一个p标签</p>}/>);

(3)兄弟组件通讯

(4)context

过程:

案例:

4、 props深入

(1)children 属性

(2)props校验

1安装使用

2常见约束规则

3所有约束规则

4使用案例

5props默认值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林太白

感谢打赏,你必大富大贵之人!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值