[英]How do you validate that PropTypes of a component in ReactJS are mutually inclusive?
如何為采用共同需要或根本不需要的PropType的組件定義PropType?
例如:
import React from 'react';
export default class Example extends React.Component {
constructor(props) {
super(props);
this.linkTo = this.linkTo.bind(this);
}
linkTo(url) {
return () => {
this.props.linkTo(url);
}
}
render() {
<div>
{this.props.title}
{ this.props.link &&
<button onClick={this.linkTo(this.props.link)}>Go!</button>
}
</div>
}
}
Example.propTypes = {
title: React.PropTypes.string.isRequired,
link: React.PropTypes.string,
linkTo: React.PropTypes.func
};
如果我們未指定link
或linkTo
作為道具,則僅會顯示title
。 但是,如果我們指定link
,那么我們也需要從父級傳遞linkTo
,反之亦然。
您可以編寫一個自定義的propType函數來檢查其他道具。
function propRelatedOr(otherProp, propType){
return (props, propName, componentName) => {
if (props[propName] == null && props[otherProp] == null) {
return new Error(`In ${componentName} expected either prop ${propName} or ${otherProp} to exist`);
}
if (propType) {
return propType(props, propName, componentName);
}
}
}
然后像這樣使用它:
Example.propTypes = {
title: React.PropTypes.string.isRequired,
link: propRelatedOr('linkTo', React.PropTypes.string),
linkTo: propRelatedOr('link', React.PropTypes.func),
};
您可以創建執行“與”,“異或”等功能的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.