React-组件之间的通信

在开发过程中,经常会遇到父组件和子组件之间相互通信,React子组件和父组件通信包括以下几个方面:

1,子组件调用父组件的方法
(1)子组件要拿到父组件的属性,需要通过 this.props 方法。
(2)同样地,如果子组件想要调用父组件的方法,只需父组件把要被调用的方法以属性的方式放在子组件上,子组件内部便可以通过“this.props.被调用的方法”这样的方式来获取父组件传过来的方法。

2,父组件调用子组件的方法
在 ReactJS 中有个叫 ref 的属性。这个属性就像给组件起个引用名字一样,子组件被设置为 ref 之后(比如 ref="xxx")。父组件便可以通过 this.refs.xxx 来获取到子组件了。

子组件向父组件传值
例子1:这里如下图,用户邮箱为父,绿色框为子。 父组件为用户输入的邮箱设好state,即“{email: ''}”,同时写好处理state的函数,即“handleEmail”,这两个名称随
意起;再将函数以props的形式传到子组件,子组件只需在事件发生时,调用父组件传过来的函数即可。

效果图

image.png

//  子类 - Child
import React from 'react';

export default class Child extends React.Component {

  render() {
    return (
      <div>
        请输入邮箱:<input onChange={this.props.handleEmail}/>
      </div>
    );
  }
}

// 父类 - Parent
import React from 'react';
import Child from './Child';

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: ' '
    }
  }

  handleEmail = (event) => {
    this.setState({
      email: event.target.value
    });
  }

  render() {
    return (
      <div>
        <div>用户邮箱:{this.state.email}</div>
        <Child name="email" handleEmail={this.handleEmail}/>
      </div>
    );
  }
}

例子2:有时候往往需要对数据做处理,再传给父组件,比如过滤或者自动补全等等,下面的例子对用户输入的邮箱做简单验证,自动过滤非数字、字母和"@."以外的字符。
效果图

image.png

//  子类 - Child
import React from 'react';

export default class Child extends React.Component {

  handleVal = () => {
    var val = this.refs.emailDom.value;
    val = val.replace(/[^0-9|a-z|\@|\.]/ig,"");
    this.props.handleEmail(val);
  }

  render() {
    return (
      <div>
        请输入邮箱:<input ref="emailDom" onChange={this.handleVal}/>
      </div>
    );
  }
}
// 父类 - Parent
import React from 'react';
import Child from './Child';

export default class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: 'ddd'
    }
  }

  handleEmail = (value) => {
    this.setState({
      email: value
    });
  }

  render() {
    return (
      <div>
        <div>用户邮箱:{this.state.email}</div>
        <Child name="email" handleEmail={this.handleEmail}/>
      </div>
    );
  }
}

例子3:如果还存在孙子组件的情况呢?如下图,黑框为父,绿框为子,红框为孙,要求子孙的数据都传给爷爷。原理一样的,只是父要将爷爷对孙子的处理函数直接传下去。
效果图

image.png
import React from 'react';
class Grandson extends React.Component {
  render() {
    return (
      <div>性别:
        <select onChange={this.props.handleSelect}>
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>
    );
  }
}

export default class Child extends React.Component {

  render() {
    return (
      <div>
        姓名:<input onChange={this.props.handleVal}/>
        <Grandson handleSelect={this.props.handleSelect}/>
      </div>
    );
  }
}

import React from 'react';
import Child from './Child';

export default class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      sex: ''
    }
  }

  handleVal = (event) => {
    this.setState({
      username: event.target.value
    });
  }

  handleSelect = (event) => {
    this.setState({
      sex: event.target.value
    });
  }

  render() {

    return (
      <div>
        <div>用户姓名:{this.state.username}</div>
        <div>用户性别:{this.state.sex}</div>
        <Child handleVal={this.handleVal} handleSelect={this.handleSelect}/>
      </div>
    );
  }
}

父类调用子类的函数和属性

// 子类
import React from 'react';

export default class ButtonComment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }
  }

  sendSword = () => {
    var newCount = this.state.count + 1;
    this.setState({
      count: this.state.count + 1
    });
    this.props.getSwordCount();
  }

  render() {
    return (
      <button onClick={this.sendSword}>{this.props.buttonName}</button>
    );
  }
}
// 父类
import ButtonComment from './ButtonComment';
import React from 'react';

export default class ImDaddyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sendCount: 0
    }
  }


  getSwordCount = () => {
    this.setState({sendCount:this.refs.getSwordButton.state.count + 1});
  }

  sendSword = () => {
    this.refs.getSwordButton.sendSword();
  }

  render() {
    return (
      <div>
        <ButtonComment ref="getSwordButton" getSwordCount={this.getSwordCount} buttonName="儿子送宝刀"/>
        <button onClick={this.sendSword}>通过老爸送宝刀</button>
        <p>
          父子俩共送{this.state.sendCount}把宝刀!!!
        </p>
      </div>
    );
  }
}

效果图

Snip20171012_1.png
Snip20171012_2.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天来看一下react组件之间是怎么进行通讯的。react推崇的是单向数据流,自上而下进行数据的传递,但是由下而上...
    亲亲qin阅读 6,020评论 2 12
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,302评论 25 708
  • 记得几个月前的王宝强吗?因为马蓉的出轨而变得妇孺皆知,远远超过了作为演员的他在国民心中的名声;超级丹赛场上英姿飒爽...
    清浅光阴阅读 707评论 0 2
  • Python中如何获取程序运行的文件夹目录的绝对路径
    AlexZhao阅读 516评论 0 6
  • 那应该是这么多年 第一次真正意义上被梦惊醒 流泪 抽泣 无法喘息 生生把自己拉回了现实 醒来 枕头已经湿透 看一眼...
    Madejorce阅读 212评论 0 0