react-6-6.复合组件,组件通信

父传子

class Test extends React.component{
  reder() {
    let {title} = this.props

    return (
      <h4>
       {title}
      <h4/>
    )
  }
}

// 父组件
ReactDOM.render(<>
  <Test title = {'帅子'}/>
</>,document.getElementById('root')
);

父组件通过属性来传值给子组件

1:只能父亲调用子组件的时候传递(只能父传子, 属于单向的)

2:但是可以基于回调函数的机制实现’子改父’
=> 把父组件中的一个方法,当作属性传递给子组件
=> 子组件接收到这个方法
=> 再子组件把这个方法执行, 从而实现对父组件中的一些信息修改

子传父

class Test extends React.component{
  reder() {
    let {title} = this.props

    return (
      <h4 onClick={
        this.props.changes.bind(this,'0')
      }>
       {title}
      <h4/>
    )
  }
}

// 父组件
class App extends React.component{
  reder() {
    let {title} = this.props

  changes(name){
    console.log(name)
  }

    return (
      <Test title={'帅子'} changes={changes} />
    )
  }
}

执行上下文

context
// 父组件
// 在组件元素上注册后代需要使用的信息
// 设置类型
static childrentextTypes = {
  title: PropsTypes.string
}

getChildContext() {
  // => getChildContext会在第一次属性和状态都初始化之后执行, 和组件重新执行渲染的时候执行(保证使用的属性和状态是最新的)
  return {
    title: this.state.tite
  }
}

// 获取上下文中的信息使用
// 设置属性
static contextTypes
 ={
  title: PropsTypes.string
}

let {title} = this.content

祖先和后台, 或者具备共同祖先的兄弟或者不相关的组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值