使用PropTypes检查字符串类型的props是否为有效的JSON

问题描述 投票:1回答:1

如何使用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.??? }

javascript reactjs react-proptypes
1个回答
0
投票
在检查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.'); } } }
© www.soinside.com 2019 - 2024. All rights reserved.