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