react 组件通信

来源:互联网 发布:侠义 知乎 编辑:程序博客网 时间:2024/06/06 19:38

react写了差不多有三个多月了,从刚开始的一脸懵逼,一点一点爬坑,学习,到现在感觉做一般的项目没什么大问题,我聊一下组件之间的通信吧

组件通信分为两种父子组件和任意组件


1:父子组件

父子组件之间的通信主要依靠props


class Parent extends Component {    constructor(props) {        super(props);        this.state={            data:'1',        }    }    onchange=(v)=>{        console.log(v);//2    }    render() {        return (            <div>                <Child data={this.state.data} onchange={this.onchange}/>            </div>        );    }}
class Child extends Component {    constructor(props) {        super(props);        this.state={            data:'2',        }    }    handleclick=()=>{        this.props.onchange(this.state.data);    }    render() {        return (            <div onClick={this.handleclick}>                {this.props.data}{/*1*/}            </div>        );    }}
上面的父组件parent把data:'1'传到了子组件child,子组件接收用props.

如果子组件想给父组件传数据,可以用父组件传过来的方法onchange,通过this.props.onchange(),通过传参的方式,将数据传递到父组件,这是最正规的方法。

当然还有一种方法使用ref,父组件可以通过ref直接调取子组件的方法,但是由于react是单向数据流,这样违背了react的本意,所以不推荐这种写法,了解即可。


2:任意组件之间的通信

任意组件之间现在react官方也没有给出什么,我在项目中是通过global处理的,即通过全局变量来保存组件的数据,以便供其他组件使用.



原创粉丝点击