• React 非嵌套组件event传值


    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}/>
            )
        }
    }
    
  • 相关阅读:
    【OpenXml】Pptx的边框虚线转为WPF的边框虚线
    C#系列文章索引
    了解LINQ
    【爬虫系列】2. 打开App逆向“潘多拉魔盒”
    Makefile基础
    设计原则 开闭原则
    设计模式 工厂方法模式
    设计原则 接口隔离原则
    设计原则 迪米特法则
    设计原则 单一职责原则
  • 原文地址:https://www.cnblogs.com/chengyunshen/p/12605801.html
Copyright © 2020-2023  润新知