zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    PHP获取一周的日期
    关系型数据库和非关系型数据库的区别和特点
    关系型数据库和非关系型数据库的特性以及各自的优缺点
    什么是数据库?什么是关系数据库?什么是非关系型数据库?
    PHP中把对象转数组的几个方法
    验证银行卡号
    xss过滤方法
    PHP 随机字符
    计算两个日期相差年月日
    判断一个时间段是否包含周末
  • 原文地址:https://www.cnblogs.com/cazj/p/11126625.html
Copyright © 2011-2022 走看看