在React.js中使用propTypes


使用propTypes可以確保元件接收props的型別安全,並有助於進行正確的計算。

示例 - 如果我們接收name作為字串,age作為數字,那麼應該以相同的型別接收。如果我們以字串形式接收age,則可能導致計算錯誤。

要使用propTypes,我們必須安裝以下軟體包。

npm install –save prop-types

此軟體包由React團隊提供。要在元件上使用它,我們將首先匯入它。

import PropType from ‘prop-types’;

我們可以在任何型別的元件(有狀態或無狀態)上使用它。

在匯出元件之前,在元件的末尾,我們這樣寫:

Player.propTypes={};
Note the propType on name of component as shown above.
Player.propTypes={
   age:PropType.number,
   name:PropType.string
}

使用JavaScript物件,我們指定prop的名稱及其有效資料型別。如果我們傳遞不正確的數

可用的prop型別如下:

  • any => 它可以是任何型別
  • Boolean (布林值)
  • String (字串)
  • Number (數字)
  • func => 表示函式
  • array (陣列)
  • object (物件)
  • symbol (符號)

如果prop型別不匹配,在瀏覽器控制檯中顯示警告訊息將幫助開發人員糾正其錯誤。

雖然我們可以在每個元件上使用proptype,但是如果元件將被其他開發人員使用並且大量使用資料型別,則應該使用它。

使用Ref

我們可以透過使用ref來掌握dom元素來操作它。

<input value={this.props.name}
ref={(myInput)=>{this.testInput=myInput}}/>
we can use it on componentDidMount
componentDidMount(){
   this.testInput.focus();
}

使用Ref的另一種最新方法

Inside constructor we can create a ref
constructor(props){
   super(props);
   this.testInputRef=React.createRef();
}

我們可以在輸入元素上使用建立的ref,如下所示:

<input value={this.props.name}
ref={this.testInputRef }/>

如何在componentDidMount中訪問這種新方法

componentDidMount(){
   this.testInputRef.current.focus();
}

我們必須在ref元素上使用current才能使其工作。

這樣,我們可以避免建立匿名函式來為輸入建立引用。

使用hook在函式式元件中建立ref

We can create ref using useRef
import React, { useRef} from ‘react’;
const myFunction=(props)=>{
   const inputRef = useRef(null);// we can give some value to ref using its constructor
}

我們可以像之前在有狀態元件中建立的那樣使用ref。

請注意,此時不應立即使用此ref,因為jsx程式碼尚未準備好。

我們可以在useEffect內部使用ref元素。useEffect函式在jsx程式碼渲染後執行,因此我們可以確保ref變數已附加到實際元素並可以使用。

這些refs將像上面一樣使用current關鍵字訪問。

This.inputRef.current.click();

透過建立ref,我們正在元件中保留一個可變欄位以便輕鬆處理它。

請注意,ref的更改不會觸發重新渲染。有一個useCallback方法可以非同步通知更改。

更新於:2019年9月4日

192 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.