如何使用props
包检查类型为[[string的placeholderProp prop-types
是否为有效的JSON?
<Component placeholderProp={'{"a":1}} />
Component.js
import React from "react" import PropTypes from "prop-types" const Component = ()=>{ ... } Component.propTypes= { placeholderProp: PropTypes.??? }
prop-types
的github页面之后,我意识到解决方案是通过使用功能:
import React from "react"
import PropTypes from "prop-types"
const Component = ()=>{ ... }
Component.propTypes= {
placeholderProp: function(props, propName, componentName) {
try {
JSON.parse(props[propName]);
} catch (e) {
return new Error('Invalid prop `' + propName + '` supplied to `' + componentName + '`. Validation failed.');
}
}
}