Get the type of React components propTypes definition

别来无恙 提交于 2019-12-05 12:45:43

Short answer, you can't compare these, because they point to different functions. When you call oneOf, it returns another function.

Explanation: The problem here is that React.PropTypes.oneOf is the function createEnumTypeChecker.

Whereas React.PropTypes.myEnum will contain the return value of calling the oneOf function - because in the propTypes definition you have to actually call oneOf().

The result of calling oneOf() is a different function, declared inside createChainableTypeChecker().

Unfortunately, your second try, won't work either because these functions are different, they're created each time you call oneOf(). See createChainableTypeChecker in ReactPropTypes.js

 var chainedCheckType = checkType.bind(null, false);
 chainedCheckType.isRequired = checkType.bind(null, true);

 return chainedCheckType;

Solution: I propose you test the names of the functions. This will prove that this is a valid React Prop type.

// returns false
React.PropTypes.oneOf(['myArr']) === React.PropTypes.oneOf(['myArr'])

// returns true
React.PropTypes.oneOf(['myArr']).name == React.PropTypes.oneOf(['myArr']).name

// this should return true in your case:
if ( TestComponent.propTypes.myEnum.name === React.PropTypes.oneOf().name )

Unfortunately, all non-primitive React propTypes use createChainableTypeChecker, and this always returns a function with the name checkType. If this name would be different for each propType, then you would be able to check which type is used. As it is now, you can't know if it's oneOf, objectOf or any of the others, including any.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!