0
点赞
收藏
分享

微信扫一扫

❤ React05-React 组件进阶

❤ React05-React 组件进阶

image.png

5-1 组件通讯介绍

image.png

5-2 组件的props

image.png

函数组件props

image.png

类组件this.props

image.png

组件props三个特点:

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

image.png

5-3 组件通讯的三种方式

父子、子父、兄弟组件

image.png

(1)传递方式1

image.png

(2)传递方式2

image.png

image.png

案例

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)兄弟组件通讯

image.png

(4)context

image.png

image.png

image.png

过程: image.png

案例: image.png

image.png

5-4 props深入

(1)children 属性

image.png

(2)props校验

image.png

image.png

1安装使用

image.png

2常见约束规则

image.png

3所有约束规则

image.png

4使用案例

image.png

5props默认值

image.png

举报

相关推荐

0 条评论