var observer = { // 观察者模式
arr: {},
$on (event, cb) { // 监听与注入函数
if (!this.arr[event]) {
this.arr[event] = [cb]
} else {
this.arr[event].push(cb)
}
},
$emit (event, ...msg) { // emit函数 与注入参数
if (this.arr[event]) {
this.arr[event].forEach(function (cb) {
cb(...msg)
}, this)
}
},
$destory (event) {
delete this.arr[event]
}
}
export default observer
父组件:
import React, { Component } from 'react'
import { Route } from 'react-router-dom'
import Popup from './common/Popup'
import observer from '../tool/observer'
class Index extends Component {
static contextTypes = {
router: PropTypes.object
}
constructor (props, context) {
super(props, context)
this.state = {
showPopup: 1
}
observer.$on('change', (state) => {
this.setState({
showPopup: state
})
})
}
}
子组件:
import React, { Component } from 'react'
import style from '../../css/popup.module.scss'
import observer from '../../tool/observer'
export default class Popup extends Component {
constructor (props) {
super(props)
this.state = {
state: !0
}
}
changeType (state) {
observer.$emit("change", state)
}
render() {
return (
<div className={style.popop}>
<h3>{this.props.message}</h3>
<p>
<button onClick={()=>this.changeType(3)}>确定</button>
<button onClick={()=>this.changeType(4)}>取消</button>
</p>
</div>
)
}
}