React 父子组件传值,defaultProps,PropTypes

1.父子向子组件传值,可以传值,也可以传方法,也可以传整个组件this

<Child title={this.state.title}/>

// this.state.title是父级的state数据,传入属性的方式传值给子组件

2.子组件获取值

class Child extends Component{
    constructor(props){
        super(props)
    }
    render(){
        return(
            <div>{this.props.title}</div>
        )
    }
}

// this.props可以获取父级传过来的属性

3.子组件向父组件传值,是通过父组件属性传过来的方法的参数进行传值

//父组件

<Child title={this.state.title} callback={this.getChildMsg}/>

getChildMsg=(msg)=>{

   console.log(this)
   console.log(`子组件的数据${msg}`)

}

//getChildMsg是父组件的方法,传给子组件回调




//子组件

<button onClick={this.props.callback.bind(this,this.state.msg)}>传值给父级</button>

//通过props获取传过来的方法,进行参数传值给父级

4.父组件调用子组件的实例

<Child ref="cd" title={this.state.title} callback={this.getChildMsg}/>

// 通过ref进行获取

getChild=()=>{

   console.log(this.refs.cd)  //获取子组件的实例 this.refs[refName]
   console.log(this.refs.state)
}

5.设置组件的默认值

class Child extends Component{
    constructor(props){
        super(props);
        console.log(this.props)
        this.state={
            msg:"传入父级组件的数据"
        }
    }

    render(){
        return(
            <div>
                <p>{this.props.title}</p>
                <p>{this.props.name}</p>
                <button onClick={this.props.callback.bind(this,this.state.msg)}>传值给父级</button>
            </div>
        )
    }
}

Child.defaultProps={
    title:"默认标题",
    name:"默认name"
}

// 直接设置defaultProps就行,属性没有赋值时候,就会获取默认值

6.设置属性的类型

import PropTypes from "prop-types"  //引入模块

class Child extends Component{
    constructor(props){
        super(props);
        console.log(this.props)
        this.state={
            msg:"传入父级组件的数据"
        }
    }

    render(){
        return(
            <div>
                <p>{this.props.title}</p>
                <p>{this.props.name}</p>
                <button onClick={this.props.callback.bind(this,this.state.msg)}>传值给父级</button>
            </div>
        )
    }
}

Child.defaultProps={
    title:"默认标题",
    name:"默认name"
}

Child.propTypes={
    title: PropTypes.string,  //字符串
    name: PropTypes.number  //number类型
}

//类似defaultProps的定义方式

//上面title是string类型,name是number类型,所以默认值name就会报错,因为默认值是string,不匹配

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值