react 03 组件传值

一 基础

props: 父传子  单向

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';


class ParentCom extends React.Component {
  constructor(props) {
    super(props)
    this.state={
      isActive: true
    }
    
  }
  render() {
    return (
      <div>
        <button onClick={()=>{this.show()}}> 控制子组件显示或隐藏(有无子组件,,,也可以通过样式来控制)</button>
        <ChildCom isActive={this.state.isActive} />
      </div>
    )
  }
  show() {
    this.setState({
      isActive:!this.state.isActive
    })
  }
}

class ChildCom extends React.Component {
    constructor(props) {
    super(props)
    this.state={} 
  }
  render() {
    if(this.props.isActive) {
      return (
        <div>子组件</div>
      )
    }else {
      return null
    }
    
  }
}

ReactDOM.render(
  <div>
    <ParentCom />
  </div>,
  document.getElementById('root')
)

子传 父 单向

将子元素的数据传递给父元素,实际上就是 调用父元素的函数,传参进去
class ParentCom extends React.Component {
  constructor(props) {
    super(props)
    this.state={
      msg:null
    }
    
  }
  render() {
    return (
      <div>      
        <ChildCom  setChildData={this.setChildData} />
        { this.state.msg}
      </div>
    )
  }
  setChildData=(childData)=>{
    this.setState({
      msg:childData
    })
  }
}

class ChildCom extends React.Component {
    constructor(props) {
    super(props)
    this.state={
      childData:'我是子组件'
    } 
  }
  render() {
    return (
      <div>
<button onClick={this.sendToParent}>点击传值给父组件</button>
      
          <button onClick={()=>this.props.setChildData(this.state.childData)}>直接调用</button>
      </div>
    )
  }
  sendToParent=()=>{
    console.log(this.state.childData)
    // 将子元素的数据传递给父元素,实际上就是 调用父元素的函数,传参进去
   this.props.setChildData(this.state.childData)

  }
}

 

posted @ 2020-04-23 15:28  学习。。。  阅读(110)  评论(0编辑  收藏  举报