首页 > 技术文章 > React组件属性/方法/库属性

lyraLee 2019-12-01 14:54 原文

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;

 

推荐阅读