react中組件傳遞數據使用props

props的深入瞭解

1.props的children屬性

  • children屬性:表示組件標籤的子節點,當組件標籤有子節點時,props就會有該屬性
  • children屬性和普通的props一樣,可以是任意值(文本,react,元素,組件,甚至是函數)
  • 注:當前組件包含內容的情況下,在render方法中return回去的組件不會包含在內
props的children屬性
const App=(props)=>{
    console.log(props);
    
    return (
        <div>
            props的children屬性
            {props.children}
        </div>
    )
}
ReactDOM.render(<App>children</App>,document.getElementById("root"))

 2.props校驗

  • 允許在創建組件的時候,指定props的類型,格式等
  • 作用:捕獲使用組件時因爲props導致的錯誤,給出明確的錯誤提示,增加組件的健壯性
  • 需要用到prop-types這個第三方的包進行實現

使用prop-types包步驟

1.在終端中安裝 yarn add prop-types或者 npm i prop-types

2.在文件進行導入 import PropTypes from ‘prop-types’

3.使用  組件名.propTypes={

          驗證的屬性名:PropTypes.類型

}

// /導入prop-types
import PropTypes from 'prop-types'
const App=(props)=>{
    const arr=props.colors
    const lis=arr.map((item,index)=><li key={index}>{item}</li>)
    return (
        <div>
            <ul>
            {lis}
            </ul>
            
        </div>
        
    )
}
// 使用prop-types添加屬性的校驗規則
App.propTypes={
    colors:PropTypes.array
}
ReactDOM.render(<App colors={['red','blue']}/>,document.getElementById("root"))

props校驗規則

1.創建類型:array,bool,func,number,object,string

2.React元素類型:element

3.必填項:isRequired

特定的結構對象:shape({})驗證規則可以寫多個,作爲對象進行傳遞

import PropTypes from 'prop-types'

const App = props => {
  return (
    <div>
      <h1>props校驗:</h1>
    </div>
  )
}

// 添加props校驗
// 屬性 a 的類型:      數值(number)
// 屬性 fn 的類型:     函數(func)並且爲必填項
// 屬性 tag 的類型:    React元素(element)
// 屬性 filter 的類型: 對象({area: '上海', price: 1999})
App.propTypes = {
  a: PropTypes.number,
  fn: PropTypes.func.isRequired,
  tag: PropTypes.element,
表示屬性filter中的area的驗證規則和price的驗證規則
  filter: PropTypes.shape({
    area: PropTypes.string,
    price: PropTypes.number
  })
}

ReactDOM.render(<App fn={() => {}} />, document.getElementById('root'))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章