react props 父組件向子組件傳參

基本用法

父組件通過在組件上綁定屬性,向子組件傳遞參數,所有的類型基本上都可以傳,函數,對象,數組,基本參數類型等

只不過傳遞非字符串參數必須通過js所以得加{}
標籤裏面的內容,可以在子組件中通過調用this.props.children得到
綁定在標籤上的參數,可以通過在子組件中調用this.props得到

function App() {
  return (
    <div>
      <PropsChildren name="小李" 
      age={20} 
      other={{sex:'男',love:'楊',fu:() => {console.log('這是傳給子組件的方法')}}}>
        這是子組件中調用this.props.children 的內容</PropsChildren>
    </div>
  );
}

子組件代碼

export default class PropsChildren extends React.Component {
  componentDidMount () {
    this.props.other.fu() //調用父組件傳過來的函數
    console.log(this.props)
  }
  render() {
    return (
    <div>{this.props.children}</div> //直接將父組件對應標籤內的內容拿過來
    )
  }
}

基本用法介紹完畢,擴展用法感興趣的同學繼續看!!!

在實際的開發中你可能需要在子組件中限制父組件傳遞過來的參數類型,typescript語法可以完美解決,不會typescript語法的同學,可以嘗試使用react的擴展 prop-types

安裝 prop-types

 npm install --save prop-types

在需要使用的子組件中導入

 import propTypes from 'prop-types';

定義子組件接受的參數類型

PropsChildren.propTypes = {
  x:propTypes.number,
  y:propTypes.number
  //這裏定義了子組件接收的x和y必須都是number類型
}

完整的子組件代碼

import React from 'react';

import propTypes from 'prop-types';
export default class PropsChildren extends React.Component {
	
	static propTypes = {
	  x:propTypes.number.isRequired,
	  y:propTypes.number.isRequired 
	}
	//這種定義類型的方式也可以
  render() {
    return (
    <div>{this.props.x+this.props.y}</div>
    )
  }
}
//這兩種定義參數類型的方式選一個
PropsChildren.propTypes = {
  x:propTypes.number.isRequired,
  y:propTypes.number.isRequired //規定了類型,並且必須傳
}

錯誤的父組件傳參示範

function App() {
  return (
    <div>
      <PropsChildren name="小李" 
      x={1}
      y="2"
      >
        這是子組件中調用this.props.children 的內容</PropsChildren>
    </div>
  );
}

瀏覽器會報錯提示開發者
在這裏插入圖片描述
通過prop-types在子組件中給參數設置默認值
class創建的組件,推薦使用

  static defaultProps = {
    x: 1,
    y: 2
  }

function可以通過es6語法設置默認值,或者

PropsChildren.defaultProps= {
	x:1,
	y:2
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章