父子组件通信方式
父传子:属性 子传父:回调方法 父组件
export default class Father extends Component {
state = {
isShow: true
}
render() {
return (
<div>
<NaviBar event={()=>{
console.log('父组件的定义的event事件');
}}></NaviBar>
{this.state.isShow && <SideBar></SideBar>}
</div>
)
}
}
子组件
import React, { Component } from 'react'
class NaviBar extends Component {
render() {
return (
<div style={{background:'skyblue'}}>
导航栏
<button onClick={() => {
console.log('子通知父,父的内部状态更新', this.props.event);
this.props.event() //调用父的回调函数
}}>导航栏按钮</button>
</div>
)
}
}
class SideBar extends Component {
render() {
return <div style={{background:'red', width:'200px'}}>
侧边栏
<div>
hhhhhhhhh
</div>
<div>
hhhhhhhhh
</div>
<div>
hhhhhhhhh
</div>
</div>
}
}
非父子间组件通信
1、状态提升(或者叫中间人)
class FilmDetail extends Component {
render() {
return (
<div className='film-detail'>
{this.props.synopsis}
</div>
)
}
}
class FilmItem extends Component {
render() {
// 结构对象
// console.log(this.props);
let {name, poster, synopsis} = this.props
return (
<div className='film-item' onClick={() => {
this.props.recieveSynopsis(synopsis)
}}>
06-中间人模式--{name}
<img src={poster} alt={name} />
</div>
)
}
}
export default class Intermediary extends Component {
state = {
synopsis:''
}
constructor() {
super()
this.state = {
cinemaLists:[]
}
axios({
url: 'https://m.maizuo.com/gateway?cityId=230100&pageNum=1&pageSize=10&type=1&k=5955436',
headers: {
'X-Client-Info':'{"a":"3000","ch":"1002","v":"5.2.1","e":"16933775432950500798431233","bc":"230100"}',
'X-host':'mall.film-ticket.film.list'
},
method: 'get'
}).then(res => {
console.log(res.data.data.films);
this.setState({
cinemaLists: res.data.data.films
})
}).catch(err => {
console.log(err);
})
}
render() {
return (
<div>
{
this.state.cinemaLists.map(item =>
<FilmItem key={item.filmId} {...item} recieveSynopsis={(synopsis) => {
this.setState({
synopsis: synopsis
})
}}></FilmItem>
)
}
<FilmDetail synopsis={this.state.synopsis}></FilmDetail>
</div>
)
}
}