ReactJS - 靜態 propTypes 屬性



我們可以在 React 中使用“propTypes”來定義我們的元件應該接收的屬性 (props) 的型別。這確保了只向我們的元件提供正確的資訊,使我們的程式碼更安全。

PropTypes 可以被認為是表達我們的元件期望接收什麼型別的資訊的一種方式。這相當於告訴我們的元件:“嘿,我期望某種型別的資料,所以確保我們得到它!”

換句話說,我們可以說 PropTypes 是 React 中用於對傳遞給 React 元件的 props 進行型別檢查的一種方法。它透過為每個引數定義預期型別來幫助開發人員檢測常見問題。propTypes 屬性作為靜態屬性新增到 React 元件類中,這意味著它與類相關聯,而不是與類的例項相關聯。

匯入 propTypes

import PropTypes from 'prop-types';

示例

示例 1

因此,我們正在建立一個小型 React 應用程式,使用靜態 propTypes 來定義我們的元件將需要的 props 型別。讓我們建立一個基本的應用程式,它接受我們的姓名並進行問候。

import React from 'react';
import PropTypes from 'prop-types';

class Greeting extends React.Component {
   // Define propTypes
   static propTypes = {
      name: PropTypes.string.isRequired, // 'isRequired' means this prop is mandatory
   };   
   render() {
      return (
         <div>
            <h1>Hello, {this.props.name}!</h1>
         </div>
      );
   }
}
class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         userName: '',
      };
   }   
   handleNameChange = (event) => {
      this.setState({ userName: event.target.value });
   };   
   render() {
      return (
         <div>
            <h1>Simple Greeting App</h1>
            <label>
               Enter your name:
            <input
               type="text"
               value={this.state.userName}
               onChange={this.handleNameChange}
            />
            </label>
            {/* Render the Greeting component and pass the name as a prop */}
            <Greeting name={this.state.userName} />
         </div>
      );
   }
}

export default App;

輸出

simple greeting app

在這個示例中,我們有兩個元件:Greeting 和 App。Greeting 元件需要一個名為 name 的字串型別 prop,它被標記為 isRequired,表示它必須被提供。

App 元件是一個簡單的應用程式,我們可以在其中將我們的姓名輸入到輸入框中。然後,給定的姓名作為 prop 傳送到 Greeting 元件,Greeting 元件顯示一個問候訊息。

在啟動此應用程式之前,請記住設定我們的 React 環境並安裝必要的包,包括 prop-types。

示例 2

讓我們再建立一個小型 React 應用程式,它使用靜態 propTypes。這次讓我們建立一個 Counter 應用程式。Counter 元件將顯示一個數字作為 prop。如果未指定數字,則將其設定為 0。

import React from 'react';
import PropTypes from 'prop-types';

class Counter extends React.Component {
   // Define propTypes for the Counter component
   static propTypes = {
      number: PropTypes.number.isRequired,
   };   
   render() {
      return (
         <div>
            <h2>Counter: {this.props.number}</h2>
         </div>
      );
   }
}
class CounterApp extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         count: 0,
      };
   }   
   handleIncrement = () => {
      this.setState((prevState) => ({ count: prevState.count + 1 }));
   };
   
   handleDecrement = () => {
      this.setState((prevState) => ({ count: prevState.count - 1 }));
   };   
   render() {
      return (
         <div>
            <h1>Simple Counter App</h1>
            {/* Render the Counter component and pass the count as a prop */}
            <Counter number={this.state.count} />
         
            <button onClick={this.handleIncrement}>Increment</button>
            <button onClick={this.handleDecrement}>Decrement</button>
         </div>
      );
   }
}

export default CounterApp;

輸出

simple counter increment

在這個應用程式中,我們建立了一個 Counter 元件,其中包含 number prop 的 propTypes。CounterApp 元件在其狀態中維護一個計數以及用於增加和減少計數的按鈕。Counter 元件顯示當前計數。

示例 3

讓我們再建立一個小型 React 應用程式,它使用靜態 propTypes。這次,我們將建立一個 ColorBox 元件,它將顏色作為 prop 並顯示一個彩色框。

import React from 'react';
import PropTypes from 'prop-types';

class ColorBox extends React.Component {
   // Define propTypes for the ColorBox component
   static propTypes = {
      color: PropTypes.string.isRequired,
   };   
   render() {
      const boxStyle = {
         width: '100px',
         height: '100px',
         backgroundColor: this.props.color,
      };
      
      return (
         <div>
            <h2>Color Box</h2>
            <div style={boxStyle}></div>
         </div>
      );
   }
}
class ColorBoxApp extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         selectedColor: 'blue',
      };
   }   
   handleColorChange = (event) => {
      this.setState({ selectedColor: event.target.value });
   };   
   render() {
      return (
         <div>
            <h1>Color Box App</h1>
            <label>
               Select a color:
               <select value={this.state.selectedColor} onChange={this.handleColorChange}>
                  <option value="red">Red</option>
                  <option value="green">Green</option>
                  <option value="blue">Blue</option>
               </select>
            </label>
            
            <ColorBox color={this.state.selectedColor} />
         </div>
      );
   }
}

export default ColorBoxApp;

輸出

color box app

在這個應用程式中,ColorBox 元件對 color prop 有 propTypes 要求。ColorBoxApp 元件在其狀態中維護一個選定的顏色並提供顏色選擇下拉選單。然後使用 ColorBox 元件根據已選顏色顯示彩色框。

總結

PropTypes 是 React 的一項功能,它允許我們定義元件將接收的屬性 (props) 的預期型別。它透過允許開發人員在開發之前指定 props 的資料型別來幫助檢測潛在的問題。

reactjs_reference_api.htm
廣告