首页 > 解决方案 > 如何在 React 组件中强制设置属性?

问题描述

是否有任何最佳实践可以在 React 组件中强制设置属性?

还有无论如何将属性设置为不可为空,所以它不会是nullor undefined

标签: javascriptreactjscomponents

解决方案


React 有一些内置的类型检查能力,通过使用prop-types包(阅读更多

import PropTypes from 'prop-types';

class MyComponent extends React.Component {
  render() {
    const myProp = this.props.myProp;
    return (
      <div>
      </div>
    );
  }
}

MyComponent.propTypes = {
  myProp: PropTypes.string.isRequired
};

请记住,这种类型检查仅在开发模式下进行。


推荐阅读