关于React父子组件间的通信

1. 父组件向子组件通信

通过props

父组件内容

import React, { Component } from 'react'
import Child from './component/Child/index'

export default class app extends Component {

  state = {
    msg: '我是父组件'
  }

  render() {

    const { msg } = this.state

    return (
      <div>
        <Child msg={msg}/>
      </div>
    )
  }
}

子组件的内容

import React, { Component } from 'react'

export default class Child extends Component {
  render() {

    const { msg } = this.props

    return (
      <div>
        <h2>{ msg }</h2>
      </div>
    )
  }
}

2.子组件向父组件通信

通过props和触发回调函数

父组件内容

import React, { Component } from 'react'
import Child from './component/Child/index'

export default class app extends Component {

  state = {
    msg: ''
  }

  onHandel = (val) => {
    const { msg } = this.state
    this.setState({msg: msg})
  }

  render() {
    const {msg} = this.state
    return (
      <div>
        <Child onHandel={this.onHandel} />

        <h2>{msg}</h2>
      </div>
    )
  }
}

子组件的内容

import React, { Component } from 'react'

export default class Child extends Component {

  onHandelChid = () => {
    this.props.onHandel('我是子组件传过来的值')
  }

  render() {
    return (
      <div>
        <button onClick={this.onHandelChid}></button>
      </div>
    )
  }
}

你可能感兴趣的:(react.js,react.js,javascript,前端)