React (8 组件间的通讯) | 您所在的位置:网站首页 › react组件的通讯方式 › React (8 组件间的通讯) |
React ——组件之间的通讯
在我们使用React开发项目的时候组件之间的通讯是必不可少的,组件之间的通讯大概分为以下几种: 父子组件之间的传值兄弟组件的传值多层嵌套组件的传值 一、父子组件之间的通讯 父组件向子组件传递参数 import React from 'react'; import ReactDOM from 'react-dom'; import reportWebVitals from './reportWebVitals'; // 子组件 class Son1 extends React.Component { constructor(props) { super(props) this.state = { content: 'son1' } // 在constructor中使用props需要在增加接收参数 console.log(props); } render () { return ( //this.props.title接收父组件传过来的值 {this.props.title} ) } } class Parent extends React.Component { constructor() { super() this.state = { title: 'parent' } } render () { return ( {/* 向子组件传值 */} constructor(props) { super(props) this.state = { content: 'son1' } // 在constructor中使用props需要在增加接收参数 console.log(props); } getMsg () { // 给子组件传递数据 this.props.msg(this.state.content) } render () { return ( //this.props.title接收父组件传过来的值 {this.props.title} constructor() { super() this.state = { title: 'parent' } } // 接收子组件传递的数据并处理 getdata (msg) { console.log('接收到数据' + msg); this.setState({ title: msg }) } render () { return ( {/* 向子组件传值 */} {this.state.title} this.getdata.bind(this)} /> ) } } ReactDOM.render( , document.getElementById('root') ); reportWebVitals();
子组件向父组件传递数据利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数传递给父组件 二、兄弟组件的传值将共享状态(数据)提升到最近的公共父组件中,由公共父组件管理这个状态,这个称为状态提升 公共父组件职责: 1. 提供共享状态 2. 提供操作共享状态的方法 要通讯的子组件只需要通过props接收状态或操作状态的方法 通过一个实例来演示 实现目的:让子组件2使用子组件1的内容 实现思路:子组件1传递数据给父组件,然后由父组件传递给子组件2并使用。 import React from 'react'; import ReactDOM from 'react-dom'; import reportWebVitals from './reportWebVitals'; // 子组件2 class Son2 extends React.Component { render () { return ( {/* 展示子组件1的title(son1)内容 */} {this.props.title} ) } } // 子组件1 class Son1 extends React.Component { constructor(props) { super(props) this.state = { content: 'son1' } } transferData () { this.props.setData(this.state.content) } render () { return ( constructor() { super() this.state = { title: '' } } // 接收son1组件传递的数据 getData (data) { console.log(data); this.setState({ title: data }) } render () { return ( this.state.title} /> ) } } ReactDOM.render( , document.getElementById('root') ); reportWebVitals(); 三、多层嵌套组件的传值在我们遇到多层嵌套组件的情况下最底层组件想用最顶层组件的值,我想到的第一个方法就是一个一个的传,但是这样很麻烦所以我就发现了Context 使用Context解决多层嵌套组件的传值 const {Provider,Consumer} = React.createContext()设置value属性,表示想要传递的数据 哪一层想要接收数据,就用Consumer进行包裹,在里面回调函数中的参数就是传递过来的值 {data=> data参数表示接收到的数据 -- {data} } |
CopyRight 2018-2019 实验室设备网 版权所有 |