DoraCMS

您现在的位置是:首页>文档内容页

文档详情

ReactJs组件通信

doramart 2016-04-22 14:53:28 ReactJS228188
说的看起来高大上,其实一讲就明白,组件通信包含了父与子组件通信,子与父组件通信,以及事件总线通信3种。

1、父与子组件通信:


我们写一个最简单的组件解释:

html (index.html):

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../react/react.js"></script>
    <script src="//cdn.bootcss.com/react/0.14.7/react-dom.min.js"></script>
    <script src="//cdn.bootcss.com/babel-core/5.8.24/browser.min.js"></script>
</head>
<body>
<div id="container"></div> 
<script type="text/babel" src="app.js"></script>


我们引入react依赖的js和browser来对jsx语法解析。引入 app.js来写react组件

const list = [
    'AAA',
    'BBB',
    'CCC',
    'DDD'
];

const Item = React.createClass({
    render(){

        const style = this.props.actived ? {border:'1px solid green'} : {};
        return <li onClick={this.props.callBack} style={style}>{this.props.name}</li>;

    }
});

const Comp =  React.createClass({

    getInitialState(){

        return {
            list : []
        }

    },

    componentWillMount(){

        this.state.list = this.props.data.map(item=>{
            return {
                actived : false,
                name : item
            }
        })
    },

    componentDidMount(){

        console.log('list',this.state.list);
        setTimeout(()=>{
            this.state.list[1].actived = true;
            this.forceUpdate();
        },3000)

    },

    callBack(item){
        console.log(item.name);
    },

    render(){

        return <ul>
            {this.state.list.map(item=> <Item callBack={this.callBack.bind(this,item)} actived={item.actived} name={item.name}/>)}
        </ul>

    }

});

ReactDOM.render(
    <div>
        <Comp name="comp one" data={list}/>
        <Comp name="comp two" data={list}/>
    </div>,
    document.getElementById('container')
);


这里我们定义了Comp 组件,给了name和data属性,在组件加载前初始化数据(componentWillMount),通过this.props.data.map的方式获取父类的属性值进行遍历。


2、子组件与父通信:

子组件如何调用父组件呢? 我们在父组件Comp的render中 Item 上加入 

callBack={this.callBack.bind(this,item)}

bind自身并传递item参数,同时在父组件中完善callBack方法:

callBack(item){
        console.log(item.name);
    },


在子组件item中,通过添加点击事件

onClick={this.props.callBack}

我们就可以轻松的与父组件通信了。


2、事件总线通信:

说起来觉得不好理解,其实就是通过事件监听的方式实现,这里我们用一个插件来描述,通过bower安装eventemitter

bower install eventemitter

reactjs通信1.JPG

我们在index.html中引入eventemitter

<script src="bower_components/eventemitter/build/eventemitter.js"></script>

做一个颜色切换的小插件,插件比较弱智,但是能说明问题:

const eventbus = new eventemitter.EventEmitter();

const Comp  =  React.createClass({

    getInitialState(){
        return {
            colorIndex : 0,
            colors : ['yellow','red']
        }
    },

    componentWillMount(){
        eventbus.on('changeColor',(id,color)=>{
            if(this.props.id != id && this.state.colors[this.state.colorIndex] == color){
                this.changeColor();
            }
        })
    },

    changeColor(){
        this.setState({
            colorIndex : this.state.colorIndex ? 0 : 1
        });
        setTimeout(()=>{
                eventbus.emit('changeColor',this.props.id,this.state.colors[this.state.colorIndex])
        },1500)
    },

    render(){
        return (
            <div style={{background:this.state.colors[this.state.colorIndex],marginBottom:20}}>
                <p>{this.props.name}</p>
                <button onClick={this.changeColor}>click me</button>
            </div>
        )
    }
});

ReactDOM.render(
    <div>
        <Comp id="one" name="first Comp"/>
        <Comp id="two" name="second Comp"/>
    </div>
    ,
    document.getElementById('container')
);


这里定义了两个Comp插件,通过点击按钮来切换背景颜色,同时发送事件,更改另一个插件为不同的颜色

reactjs通信2.JPG

const eventbus = new eventemitter.EventEmitter();


来实例化一个event对象,它有两个方法: 

eventbus.on() // 事件监听

eventbus.emit() // 事件发送


了解node 事件系统的对这个就比较熟悉了。

文章评论

取消回复
登录 参与评论

评论列表(