React中组件之间相互传值

父组件给子组件传值,通过属性的方式传值

子组件如果是类

import React, { Component } from 'react';

// 1.类子组件
class ChildCpn1 extends Component {
  constructor(props) {
    super();
    this.props = props;
  }

  render() {
    const { name, age, height } = this.props;

    return (
      <div>
        <h2>我是class的组件</h2>
        <p>展示父组件传递过来的数据: {name + " " + age + " " + height}</p>
      </div>
    )
  }
}

export default class App extends Component {
  render() {
    return (
      <div>
        <ChildCpn1 name="why" age="18" height="1.88" />
      </div>
    )
  }
}

子组件如果是函数

function ChildCpn2(props){
  const {name,age,height} = props;
  return (
    <div>
      <h2>function组件哈</h2>
      <p>展示父组件传递过来的数据:{name + " "+ age+ " "+height}</p>
    </div>
  )
}

参数验证,需要导入

import PropTypes from 'prop-types';

用法如下

ChildCpn1.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  height: PropTypes.number
}

 某个属性必须的设置用法如下

requiredFunc: PropTypes.func.isRequired

设置属性的默认值为如下用法

ChildCpn1.defaultProps = {
  name: "王小波",
  age: 40,
  height: 1.92
}

子组件传递父组件

 在Vue中是通过自定义事件来完成的,但是在React中同样是通过props传递信息,只是让父组件给子组件传递一个回调函数,子组件中调用这个回调函数即可。


function CounterButton(props){
   const {operate,btnClick} = props;
   return <button onClick={btnClick}>{operate}</button>
}

export default class ParentButton extends Component {
  constructor(props){
    super(props)
    this.state = {
      counter: 0
    }
  }

  changeCounter(count){
    this.setState({
      counter: this.state.counter+count
    })
  }

  render(){
    return (
      <div>
        <h2>子组件向父组件传值的操作:{this.state.counter}</h2>
      <CounterButton operate="+1" btnClick={e=>this.changeCounter(1)}></CounterButton>
      <CounterButton operate="-1" btnClick={e=>this.changeCounter(-1)}> </CounterButton>
      </div>
      

  )

  }

}




function ChildCpn2(props){
  const {name,age,height} = props;
  return (
    <div>
      <h2>function组件哈</h2>
      <p>展示子组件传递过来的数据:{name + " "+ age+ " "+height}</p>
    </div>
  )
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值