event.js (单例)
import {EventEmitter } from 'events';
export default new EventEmitter();
app.js
import React, {Component} from 'react';
import emitter from './components/event'
class ListItem extends Component {
constructor(props){
super(props);
}
render(){
return (
<li>
<input type="checkbox" checked={this.props.checked} onChange={this.props.onChange} />
<span>{this.props.value}</span>
</li>
)
}
}
ListItem.defaultProps = {
checked:false
}
class List extends Component {
constructor(props){
super(props);
this.state = {
list: this.props.list.map(entry => ({
text:entry.text,
checked:entry.checked || false
}))
}
}
onItemChange(entry){
const {list} = this.state;
this.setState({
list: list.map(pre => ({
text: pre.text,
checked:pre.text === entry.text ? !pre.checked : pre.checked
}))
},()=>{
emitter.emit('ItemChange',{...entry,checked:!entry.checked})
})
}
render(){
return (
<div>
<ul>
{this.state.list.map((entry,index)=>(
<ListItem key={`list-${index}`} value={entry.text} checked={entry.checked} onChange={this.onItemChange.bind(this,entry)} />
))}
</ul>
</div>
)
}
}
export default class App extends Component{
state = {
list:[{text:'apple'},{text:'orange'}]
}
componentDidMount(){
this.itemChange = emitter.addListener("ItemChange",(msg,data) => {
console.log(data, msg)
})
}
componentWillUnmount(){
emitter.removeListener(this.itemChange)
}
render(){
return (
<List list={this.state.list}/>
)
}
}