javascript - 如何在 React 组件中强制设置属性?
问题描述
是否有任何最佳实践可以在 React 组件中强制设置属性?
还有无论如何将属性设置为不可为空,所以它不会是null
or undefined
?
解决方案
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
};
请记住,这种类型检查仅在开发模式下进行。
推荐阅读
- node.js - 将 trello API 与 oauth 一起使用
- react-native - 如何等待 flatlist 的所有组件执行一个函数?
- ms-word - 如何在记事本或 Word 或 Google Docs 中移动或交换此文本
- php - 如何正确包含 codeigniter websocket 库?
- php - 其他表正常时不会创建用户表
- python - Keras:自定义损失导致“您必须为占位符张量提供一个值”
- python - Nagios python脚本等待执行
- dart - 在 Dart 语言中,方法成员可以在类体之外实现吗?
- google-app-maker - 下拉菜单的默认值
- r - 将 df 转换为边 df 用于协作网络