❤ React05-React 组件进阶
5-1 组件通讯介绍
5-2 组件的props
函数组件props
类组件this.props
组件props三个特点:
① 可以给组件传递任意类型的数据 ② props是只读的对象,只能读取属性的值,无法修改对象 ③ 注意:使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取props
5-3 组件通讯的三种方式
父子、子父、兄弟组件
(1)传递方式1
(2)传递方式2
案例
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
过程:
案例: