4.父子组件

import React from 'react';
import ReactDOM from 'react-dom';
/* 
在vue中:
    父传子  其实就是通过自定义属性  子组件通过props接收
    子传父  其实就是通过自定义事件  子组件通过$emit触发父组件定义的事件 并且把子组件的数据
              通过参数的方式给了父组件;
在react中:
  父传子: 通过行内自定义属性 + this.props
  子传父: 通过行内自定义属性(对应的是一个函数) + this.props
  凡是用在组件上的属性  都是创造组件的那个人自己定义的
*/
class Button extends React.PureComponent{
  add=()=>{
    this.props.onClick(10)
  }
  minus=()=>{
    this.props.onClick(-10)
  }
  render(){
    console.log(this.props.qqq)
    return <div>
      <button onClick={this.add}>+</button>
      <button onClick={this.minus}>-</button>
    </div>
  }
}
// PureComponent 和  Component 都是react的内置组件;但是前者的性能稍高(涉及到某个钩子函数)
class Show extends React.PureComponent{
  // constructor(props){
  //   super(props)
  // }
  render(){
    // 子组件可以通过 this.props 接过来这个对象
    console.log(this.props)
    return <div className={this.props.className}>
      <h1>当前数字是{this.props.num}</h1>
    </div>
  }
}
class App extends React.Component {
    constructor() {
        super();
        this.state = {
          count:100
        }
    }
    changeCount(n){
      this.setState({
        count:this.state.count + n
      })
    }
    render() {
        let {count} = this.state;
        return <div className=''>
          {/* 把qqq:箭头函数 打包成一个对象传给了 Button组件对应的函数 */}
          <Button onClick={(n)=>{this.changeCount(n)}}/>

          <Show qqq={123} aaa={666} num={count} className='box'/>
          {/* 把qqq:123 aaa:666 num:100 打包成一个对象 传给Show组件对应的函数 */}
        </div>;
    }
}

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值