所以你想发送一个类型为 的propsobject,它必须具有属性p和h4?
如果不编写执行此检查的自定义函数,这是不可能的。为此,您可以propTypes像这样声明:
propTypes: {
content: function(props, propName, componentName) {
//do your validation here.
//Return an Error if something's wrong, otherwise don't return anything (or return null).
}
}
这是官方文档所说的:
您还可以指定自定义验证器。如果验证失败,它应该返回一个 Error 对象。不要console.warn或扔 [...]
在官方文档中阅读更多关于使用 PropTypes 进行类型检查的信息。
演示
这是我准备的演示。对于您正在寻找的内容,它可能会也可能不会过度,因为验证非常广泛。你可以挑选你需要的那些。您的以下验证content是(按顺序):
- 验证props
content是否通过。
- 验证props
content是一个object.
- 验证props
content的对象属性为p。
- 验证props
content的对象属性为h1。
- 验证对象属性
content.p是string.
- 验证对象属性
content.h1是string.
var DialogContent = React.createClass({
propTypes: {
content: function(props, propName, componentName) {
if (!props.content) {
return new Error(
'Required prop `' + propName + '` was not specified in `' + componentName + '`.'
);
} else if (typeof props.content !== 'object') {
return new Error(
'Invalid prop `' + propName + '` of type `' + typeof props.content + '` supplied to `' + componentName + '`, expected `object`.'
);
} else if (!props.content.p) {
return new Error(
'Required prop `p` of object `' + propName + '` was not specified in `' + componentName + '`.'
);
} else if (!props.content.h1) {
return new Error(
'Required prop `h1` of object `' + propName + '` was not specified in `' + componentName + '`.'
);
} else if (typeof props.content.p !== 'string') {
return new Error(
'Invalid object property `p` of prop `' + propName + '` of type `' + typeof props.content.p + '` supplied to `' + componentName + '`, expected `string`.'
);
} else if (typeof props.content.h1 !== 'string') {
return new Error(
'Invalid object property `h1` of prop `' + propName + '` of type `' + typeof props.content.h1 + '` supplied to `' + componentName + '`, expected `string`.'
);
}
}
},
render: function() {
return <div>My DialogContent Component</div>;
}
});
var obj = {
p: "foo",
h1: "bar"
};
ReactDOM.render(<DialogContent content={obj} />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
你也可以在这个Fiddle上测试它并做一些模拟。尝试更改传递给组件的值、类型和对象属性并读取控制台输出。
希望这可以帮助。祝你好运!