react——父子组件通信

本文详细介绍了React中父组件与子组件之间的数据传递和方法调用。通过具体代码示例,展示了如何在父组件中定义状态和方法,并将其传递给子组件;同时,也讲解了子组件如何访问和调用这些数据和方法。

 父组件

import React from 'react'
import TransValue from './transVlaue'
class Header extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            value: '111111111'
        }
    }
    transFun=()=>{
        alert('我是父组件的方法')
    }
    showChildData=()=>{
        alert(this.refs.childModel.state.value) // this.refs.childModel 可以理解为子组件中的this
    }
    render() {
        return (
            <div>
                <h3>头部组件</h3>
                 <-- tf代表传递过去的方法   self是将整个父组件对象传递过去 tValue是传递的变量值 -->
                <TransValue ref="childModel"  tf={this.transFun} tValue={'父组件传递过来的值'} self={this}></TransValue>
                <button onClick={this.showChildData}>获取子组件内容</button>
            </div>
        )
    }
}
export default Header

子组件

import React from 'react'
import PropTypes from 'prop-types'
class TransVlaue extends React.Component {
constructor(props) {
super(props)
this.state = {
value: '22222222222'
}
}

showParentData = () => {
alert(this.props.self.state.value) //this.props.self可以理解为父组件的this
}

render() {
return (
<div>
传值组件
<h3>{this.props.tValue}</h3>
<h4>{this.props.name}</h4>
<button onClick={this.props.tf}>调用父组件传递过来的方法</button>
<button onClick={this.showParentData}>传递整个父组件对象</button>
</div>
)
}
}

TransVlaue.defaultProps = { // 设置默认值,当父组件没有传值过来时就为默认值
name: '标题'
}
TransVlaue.propTypes={ // 设置传递值得类型,当类型不符,则会报错(首先得引入import PropTypes from 'prop-types')
num:PropTypes.number
}

export default TransVlaue

 

转载于:https://www.cnblogs.com/cazj/p/11126625.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值