日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

React中Props的使用

作者:想學(xué)好前端的小寶 更新時(shí)間: 2022-08-19 編程語(yǔ)言

Props使用

Props的基本使用

  • props傳遞接受數(shù)據(jù)

    ???1.在組件標(biāo)簽上添加屬性

    ????2.類組件使用 this.props 接收數(shù)據(jù)。函數(shù)組件使用參數(shù) props 接收數(shù)據(jù)。

    • 使用類接收數(shù)據(jù)
    // 類接受 props 數(shù)據(jù)
    class App extends React.Component {
      render() {
        return (
          <div>
            <h1>姓名:{this.props.name}</h1>
            <h1>年齡:{this.props.age}</h1>
          </div>
        )
      }
    }
    
    ReactDOM.render(<App name="Tom" age="18" />, document.getElementById('root'))
    • 使用函數(shù)接收數(shù)據(jù)
    // 函數(shù)接收 props 數(shù)據(jù)
    const App = props => {
      return (
        <div>
          <h1>姓名:{props.name}</h1>
          <h1>年齡:{props.age}</h1>
        </div>
      )
    }
    
    ReactDOM.render(<App name="Tom" age="18" />, document.getElementById('root'))
  • props 特點(diǎn)

    • 可以給組件傳遞任意類型的數(shù)據(jù)

    • props 傳遞的數(shù)據(jù)是只讀的數(shù)據(jù)。只能讀取屬性的值,而不能進(jìn)行修改。

    • 在使用類組件時(shí),若寫了構(gòu)造函數(shù),必須將 props 傳給 super()

constructor(props) {
    super(props)
    ...
}

Props深入

  • Children屬性

    • 表示組件的子節(jié)點(diǎn)。有子節(jié)點(diǎn)的時(shí)候, Props 就會(huì)有這個(gè)屬性

    • 和普通的Props 一樣,值可以是任意值

  • Props的校驗(yàn)

    • 對(duì)于組件來(lái)說(shuō) Props 是外來(lái)的,無(wú)法保證組件的使用者傳入的數(shù)據(jù)格式

    • 傳入的數(shù)據(jù)格式不對(duì)的話,會(huì)導(dǎo)致組件內(nèi)部報(bào)錯(cuò),且不知道明確的錯(cuò)誤原因

    • Props校驗(yàn):在創(chuàng)建組件的時(shí)候,會(huì)指定 Props 的類型和格式---這樣就算格式出錯(cuò)也會(huì)給出一個(gè)明確的錯(cuò)誤。

    • 使用步驟:

      • 安裝 Props-types(npm i prop-types/yarn add prop-types)

      • 導(dǎo)入prop-types 包

      • 使用 組件名.propType = {} 給組件添加校驗(yàn)規(guī)則

```javascript
import propTypes from 'prop-types'
function App(props) {
    return (
    <h1>{props.name}</h1>
    )
}
App.propTypes = {
    name : PropTypes.string
}
```
  • 約束規(guī)則

    • 常見類型: Array、number、object、string、bool、func

    • React 元素類型: element

    • 是否必填:isRequired

    • 特定結(jié)構(gòu)的對(duì)象: shape({ }) ----- 約束多個(gè)屬性的時(shí)候,整合到這個(gè)對(duì)象中一起書寫

  • Props的默認(rèn)值

    • 定義一個(gè)默認(rèn)值,不傳入數(shù)值的時(shí)候,默認(rèn)采用這個(gè)數(shù)值
    const App = props => {
        return (
           <div>props.name/div>
        )
    }
    //添加默認(rèn)值
     App.defaultProps = {
        name : 'Tom'
    }

原文鏈接:https://blog.csdn.net/weixin_51642358/article/details/126414438

欄目分類
最近更新