react开发教程之React 组件之间的通信方式

这两天学习了React感觉组件通信这个地方知识点挺多的,而且很重要,所以,今天添加一点小笔记。

父子组件通讯

通讯手段

这是最常见的通信方式,父组件只需要将子组件需要的props传给子组件,子组件直接通过this.props来使用。

通讯内容

更多要提的是如何合理的设置子组件的props,要想将子组件设计成一个复用性强的通用组件,需要将能够复用的部分抽象出来,抽象出来的props有两种形成,一种是简单的变量,另一种是抽象出来处理某种逻辑函数。

以Header 组件为例

import React,{ Component } from 'react';

class Header extends Component {
constructor() {
super();
this.handleClick = (e) => {
console.log(this)
}
}

renderLeftComponent() {

let leftDOM = {};
if (this.props.renderLeftComponent) {
  return this.props.renderLeftComponent();
}

if (this.props.showBack) {
  let backFunc = this.props.onBack || this.goBack;
  leftDOM = (<a onClick={backFunc.bind(this)}><i className="icon left-icon icon-left-arrow"&gt;</i></a>);
}
return leftDOM;

}

renderRightComponent() {
if (this.props.renderRightComponent) {
return this.props.renderRightComponent();
}
}

goBack() {
alert("返回上一页")
}

render() {
return (
<header className="header-bar">
{this.renderLeftComponent()}
{this.props.title || '滴滴'}
{this.renderRightComponent()}

); } }

export default Header;

//父亲组件部分代码App.jsx
import HeaderBar from "./components/Header";

let leftIcon = function () {
return (
<i className="icon left-icon icon-left-haha">左边按钮
)
}
class App extends Component {

render() {
return (
<div className="App">

); } }

子父组件通讯

父-子组件通信的手段是通过子组件的props是子组件用父组件的东西,子-父组件通信,是父组件用子组件的东西,暂时了解的两种方法

利用回调函数

父组件通过props传递一个方法给子组件,子组件通过props方法将子组件数据传递给父组件

利用ref

父组件通过refs调用子组件的属性

跨级组件通信

在React中当一个属性反复使用并且存在与好几个子组件中的时候,这个时候我们如果通过props一级一级传递的话可以实现多层级访问,但是这样出现一个问题就是会使代码非常混乱,在React中国年,我们还可以使用 context 来实现跨级父子组件间的通信;

在react中context称为虫洞

// add the following property
static childContextTypes = {
color: React.PropTypes.string
}

// 添加下面方法
getChildContext() {
return {
color: "#f00"
}
}

render() {

} }

// Component Child1
class Child1 extends React.Component {
// 添加下面属性
static contextTypes = {
color: React.PropTypes.string
}

render() {

{this.context.color}
} }

同级组件通信

同级组件之间的通信还是需要通过父组件作为中介,利用多次父-子组件通信,项目中将需要传递的数据放在了父组件的state中,变动时可以自动的同步传递。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小