Skip to content

Latest commit

 

History

History
188 lines (150 loc) · 2.96 KB

1.md

File metadata and controls

188 lines (150 loc) · 2.96 KB

React 组件通信

父子组件通信

父传子 通过props

// 父组件
class Parent extends React.Component {
  state = {
    name: ''
  }
  
  handleChange = e => {
    this.setState({
      name: e.target.value
    })
  }

  render () {
    return (
      <div>
        <div>爸爸说:<input type="text" onChange={this.handleChange} /></div>
        {/*
          1. 定义传参属性,sayName
        */}
        <Child sayName={this.state.name} />
      </div>
    )
  }
}

// 子组件

class Child extends React.Component {

  render () {
    return (
        {/*
          1. 通过props 取出父组件定义的属性
        */}
      <div>
        { this.props.sayName }
      </div>
    )
  }
}
  

子传父 通过回调函数

// 父组件
class Parent extends React.Component {
  state = {
    name: ''
  }
  
  handleChange = e => {
    this.setState({
      name: e.target.value
    })
  }

  childX = v => {
    // 接收子组件定义的回调函数
    this.setState({
      name: v
    })
  }

  render () {
    return (
      <div>
        <div>爸爸说:<input type="text" onChange={this.handleChange} /></div>
        {/*
          1. 定义传参属性,sayName
        */}
        <Child sayName={this.state.name} childX={this.childX} />
      </div>
    )
  }
}

// 子组件

class Child extends React.Component {

  handleChange = e => {
    // 子组自定义回调函数挂载到props上
    this.props.childX(e.target.value)
  }

  render () {
    return (
        {/*
          1. 通过props 取出父组件定义的属性
        */}
      <div>
        { this.props.sayName }

        <input type="text" onChange={this.handleChange} />
      </div>
    )
  }
}
  

爷孙组件 使用context, 爷组件childContextTypes声明需要传递数据, 执行getChildContext方法放入数据

// 父组件

import PropTypes  from 'prop-types' // 需要引入PropTypes

class Parent extends React.Component {

  // 祖先组件声明需要放入context上的数据
  static childContextTypes = {
    name: PropTypes.string
  }

  // 祖先组件往context放入数据
  getChildContext() {
    return {name: this.state.name}
  }


  state = {
    name: ''
  }
  
  handleChange = e => {
    this.setState({
      name: e.target.value
    })
  }

  render () {
    return (
      <div>
        <div>爸爸说:<input type="text" onChange={this.handleChange} /></div>
        {/*
          1. 定义传参属性,sayName
        */}
        <Child />
      </div>
    )
  }
}

// 子组件

class Child extends React.Component {
  render () {
    return (
      <div>
        <Grandson />
      </div>
    )
  }
}

// 孙子组件

import PropTypes  from 'prop-types' // 需要引入PropTypes

// 祖先组件声明需要放入context上的数据
  static childContextTypes = {
    name: PropTypes.string
  }

class Grandson extends React.Component {
  render () {
    return (
      <div>
      { this.context.name }
      </div>
    )
  }
}