Javascript 如何验证ReactJS中组件的PropType是互斥的?
我如何为一个组件定义PropTypes,该组件包含同时需要或根本不需要的PropTypes 例如:Javascript 如何验证ReactJS中组件的PropType是互斥的?,javascript,reactjs,Javascript,Reactjs,我如何为一个组件定义PropTypes,该组件包含同时需要或根本不需要的PropTypes 例如: import React from 'react'; export default class Example extends React.Component { constructor(props) { super(props); this.linkTo = this.linkTo.bind(this); } linkTo(url) {
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
};
从“React”导入React;
导出默认类示例扩展了React.Component{
建造师(道具){
超级(道具);
this.linkTo=this.linkTo.bind(this);
}
链接到(url){
return()=>{
this.props.linkTo(url);
}
}
render(){
{this.props.title}
{this.props.link&&
走!
}
}
}
示例.propTypes={
标题:React.PropTypes.string.isRequired,
链接:React.PropTypes.string,
链接到: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),
};
您可以创建执行“和”、“异或”等操作的函数版本。为什么不接受链接和链接到作为一个对象的一部分,并使其成为必需的?感谢这确实有助于创建一些自定义道具类型。