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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM