在 React 中,您可以指定需要哪些 props 以及它们应该具有哪些类型。当未知的 prop 名称(例如在 propTypes 中未指定)传递给组件时,是否有可能显示验证警告?
最佳答案
有了高阶组件,一切皆有可能:
// 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
}
});
关于javascript - react 冗余 Prop 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39416512/