单向数据流和组件通讯

react的编程思想是严谨周密的,约束了花式操做,确保在使用react构建项目的时候不会出现太多问题javascript


1、单向数据流java

  • 规范数据的流向:数据只能经过props由外层组件(父组件)向内层组件(子组件)进行传递和更新
  • 做用:下降了组件间通讯的耦合度,方便debug(直接从props中找)

props只能一层层传递,不能隔代传递, context能隔代通讯react

2、子组件和父组件通行编程

一、原理:父组件中定义函数,经过props传递给子组件,子组件调用这个函数并传参,
父组件就能够经过形参拿到子组件的数据函数

二、react的父子组件间通讯规则:this

*父传子: 父组件经过props传参呗……*
*子传父 : 父组件经过props传参呗……*debug

依然符合单向数据流的概念,无非就是把函数看成参数传递下去blog

class Child extends React.Component{
  data = '我是子组件中的data'
  render(){
    this.props.getChildData(this.data);
    return <div>我是Child组件</div>
  }
}
class Parent extends React.Component{
  childData=null
  getChildData = (data)=>{
    this.childData = data;
    console.log(data);
  }
  render(){
  return <Child getChildData = { this.getChildData } />
  }
}
console.log(<Parent />)
相关文章
相关标签/搜索