1. 程式人生 > >React 學習筆記 (四)(父子元件)

React 學習筆記 (四)(父子元件)

super

Es6中的super可以用在類的繼承中,super關鍵字,它指代父類的例項(即父類的this物件)
子類必須在constructor方法中呼叫super方法,否則新建例項時會報錯。
這是因為子類沒有自己的this物件,而是繼承父類的this物件,然後對其進行加工。
不呼叫super方法,子類就得不到this物件。

constructor(props){
        super(props);//用於父子元件傳值 用在建構函式中,必須在使用this之前呼叫
        this.state={
           name:‘小豆花兒’
        }
    }

父元件給子元件傳值

1.父元件呼叫子元件時指定屬性
傳值 title={this.state.title}
傳方法 run={this.run}
傳整個父元件 home={this}

<PageHeader title={this.state.title} run={this.run} home={this}></PageHeader>

2.子元件使用時
{this.props.title} —接收值
{this.props.home.run} —接收方法
{this.props.home} —接收整個父元件

<h2>{this.props.title}</h2>
<button onClick={this.props.run}>呼叫父元件的run方法</button><br/><br/>
<button onClick={this.props.home.getData}>獲取父元件getData方法</button><br/><br/>

父元件呼叫子元件的資料和方法

1、呼叫子元件的時候指定 ref 的值

<Header ref='header'></Header>

2、通過 this.refs.header 獲取整個子元件例項 (dom載入完成以後獲取)

getHeader=()=>{
    alert(this.refs.header.state.msg)
    this.refs.header.run()
}

defaultProps:父元件呼叫子元件不給子元件傳值,可以在子元件中使用

父元件呼叫子元件不傳值

<PageHeader></PageHeader>

子元件使用defaultProps

PageHeader.defaultProps={
  title:'標題'
}

propTypes:定義父元件給子元件傳值的型別

父元件呼叫子元件

<PageHeader num={111}></PageHeader>

子元件先引入

import PropTypes from 'prop-types';

子元件使用(注意propTypes的大小寫)

PageHeader.propTypes={
  num:PropTypes.number
}