在React中,您可以指定需要哪个道具以及它们应具有哪些类型。当未知的道具名称(例如propTypes中未指定)传递给组件时,是否有可能显示验证警告?
答案 0 :(得分:3)
使用更高阶的组件是可能的:
// This is not a full solution, merely a sketch of one way to do it
const OnlyValidProps = WrappedComponent => {
return class extends React.Component {
render() {
const actualProps = Object.keys(this.props);
const expectedProps = Object.keys(WrappedComponent.propTypes);
const hasPropMisMatch = (
actualProps.length != expectedProps.length ||
!actualProps.every(key => expectedProps.contains(key))
);
if (hasPropMisMatch) {
console.warn(`Props mismatch! expected: ${expectedProps} actual: ${actualProps}`);
}
return <WrappedComponent {...this.props} />;
}
};
}
// Usage
OnlyValidProps(class MyClass extends React.Component {
static propTypes = {
x: React.PropTypes.number,
y: React.PropTypes.number
}
});