1. 程式人生 > >元件與props簡解

元件與props簡解

一、建立元件

1.函式式建立

  特點:

  • 元件不能訪問this物件
  • 元件無法訪問生命週期的方法
  • 無狀態元件只能訪問輸入的props,無副作用
function Title() {
  return <h2>新聞列表</h2>;
}

2.繼承component類來建立元件 (一般我們用繼承React.Component類的方式來建立元件)
 特點:
  • 元件能訪問this物件
  • 元件有訪問生命週期的方法
  • 有元件狀態state
class Title extends React.Component{
  constructor(props){
    super(props);
  }
  render() {
    return <h2>新聞列表</h2>;
  }
}

二、元件渲染

單閉合呼叫(只能傳props的值)
<Title />

雙閉合呼叫 (標籤內還可以寫子標籤) 
<Title></Title>
<Title>hello word</Title> 

在元件內可以通過this.props.children獲取, 或者通過React.Children.map(this.props.children, item=>{returm <div>{item}</div>})

三.屬性

調取元件的時候,傳遞給元件的資訊(render渲染的時候會把props傳遞給元件,props就是屬性)

作用:讓元件豐富化(傳遞不同的屬性控制組件展示不同的效果)

特點:傳遞進來的屬性在元件內部不能修改,也就是它是“只讀的”。(修改屬性的值,只能重新調取元件並且重新傳遞值)

雖然不可以修改屬性值,但是在類建立元件的方式中,我們可以給元件設定預設值和設定一些規則。

import React from 'react';

import PropTypes from 'prop-types';  //使用 PropTypes 進行型別檢查

class Say extends React.Component{
  //設定預設值
  static defaultProps = {
    title: 'hello word'
  }
  //設定預設規則
  static propTypes = {
    title: PropTypes.string,
    num: PropTypes.number.isRequired
  }
  constructor(props){
    //當super中沒有傳入props時
    /**
    * 1.在呼叫元件開始執行constructor,引數props是傳遞進來的屬性資訊(而且是經過defaultProps和propTypes等處理過的)
    * 2.但是此時還沒有掛載到例項上,所以this.props的結果是undefined
    * 3.constructor結束後,掛載就完成了,所以其它生命週期函式中是可以基於this.props來獲取屬性的
    */
    // super();
    // console.log(props, this.props) //{title: "two", num: 20} undefined

    //當super中傳入props時
    /**
    * 會在當前例項上掛載很多私有屬性
    * this.props = props;
    * this.context = context;
    * this.refs = {};
    * 現在不這樣處理,當constructor執行完成,react也會幫我們給例項掛載這些屬性
    */
    super(props); //call繼承:React.Component.call(this)
    console.log(props, this.props) //{title: "two", num: 20} {title: "two", num: 20}

    //例項上還可以調取Component類的兩個方法
    /**
    * this.setState()
    * this.forceUpdate()
    */
  }
  render() {
    return (
      <p>{this.props.title}</p>
    )
  }
}
// Say.propTypes = {
// title: PropTypes.string
// }
export default Say;

<Say title={'two'} num={20}></Say>

&n