React組件屬性/方法/庫屬性


1. propTypes

用於進行props的類型檢查;來自於prop-types庫。

// V15.5之后
import PropTypes from 'prop-types';

該方法適用於函數組件和class組件。

如果使用了@babel/plugin-proposal-class-properties插件,

可以直接在組件內部作為靜態屬性。

class App extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired
  }
  render() {
    return(
      <div>{this.props.name}</div>
    )
  }
}

在組件(class組件和函數組件都適用)外部:

class App extends React.Component {
  render() {
    return(
      <div>{this.props.name}</div>
    )
  }
}
App.propTypes = {
  name: PropTypes.string.isRequired
}
// 函數組件
function App(props){
  return(
    <div>{props.name}</div>
  )
}
App.propTypes = {
  name: PropTypes.string.isRequired
}

2.defaultProps

組件的屬性。用於給props屬性賦初始值,  當屬性值為undefined時生效,null不生效。

既可以在組件內部也可以在組件外部。

運行在propTypes類型檢查前。

function App(props){
  return(
    <div>{props.name}</div>
  )
}
App.defaultProps = {
  name: "lyra"
}
ReactDOM.render(<App name={undefined} />, window.root)

3. displayName

用於React Devtools中顯示組件的名稱。

函數組件和類組件都可以使用。主要在高階組件時比較有用。

function withSubscription(WrappedComponent) {
  class WithSubscription extends React.Component {/* ... */}
  WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
  return WithSubscription;
}

4. getDerivedStateFromError(V16.6.0)

類組件的靜態方法。用於捕獲錯誤。

static getDerivedStateFromError(error)

同componentDidCatch,捕獲子組件拋出的異常。不能捕獲自身的異常。

和getDerivedStateFromProps類似,它返回一個state對象,用於下次渲染時展示降級UI,而不是崩潰的組件樹。

import React from 'react';

class ErrorBoundary extends React.Component {
  state = {
    hasError: false
  }
  // getDerivedStateFromError在“渲染階段”就會調用;
  // 不能出現副作用;如果需要,可以使用componentDidCatch
  static getDerivedStateFromError(error) {
    return {
      hasError: true
    }
  }
  render() {
    if (this.state.hasError) {
      return <h2>降級UI</h2>
    }
    return this.props.children;
  }
}

PS: 和該方法類似的有componentDidCatch

componentDidCatch(error, info)
// error是錯誤信息
// info是調用棧信息 info.componentStack

 不同點是: componentDidCatch方法中可以執行副作用。如向服務器發送錯誤日志等。

export default class ErrorBoundary extends React.Component {
  state = {
    hasError: false
  }
  static getDerivedStateFromError(error) {
    return {
      hasError: true
    }
  }
  componentDidCatch(error, info) {
    logToServer(info.componentStack)
  }
  render() {
    if (this.state.hasError) {
      return <h2>降級UI</h2>
    }
    return this.props.children;
  }
}

 5. contextType

組件設置了該屬性后,可以通過this.context訪問context對象的值。

import {ThemeContext} from './theme-context';

class ThemedButton extends React.Component {
  static contextType = ThemeContext;
  render() {
    let props = this.props;
    let theme = this.context; //最近的Provider提供的值 return (
      <button
        {...props}
        style={{backgroundColor: theme.background}}
      />
    );
  }
}

export default ThemedButton;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM