是否有任何最佳实践可以使 React 组件中的属性成为必需?
还有没有办法将属性设置为不可为空,这样它就不会是 null
或 undefined
?
最佳答案
React 通过使用 prop-types
包 ( read more ) 具有一些内置类型检查功能
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
};
请记住,此类型检查仅在开发模式下完成。
关于javascript - 如何在 React 组件中设置强制属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54305505/