【问题标题】:React redundant prop validation反应冗余道具验证
【发布时间】:2016-09-09 17:04:11
【问题描述】:

在 React 中,您可以指定需要哪些道具以及它们应该具有哪些类型。当未知的 prop 名称(例如 propTypes 中未指定)传递给组件时,是否有可能显示验证警告?

【问题讨论】:

标签: javascript validation reactjs properties


【解决方案1】:

有了高阶组件,一切皆有可能:

// 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
  }
});

【讨论】:

  • 您必须记住在返回 render 中的组件之前调用任何方法,但是是的,它肯定会。
  • 我的意思是在基类中有一个渲染方法来进行检查,而子类将从他们的渲染方法中调用 super.render。我真的想知道这样做是否有好处。
  • 不会很清楚,因为您会调用 super.render() 但忽略返回值...但您可以这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2020-01-02
  • 2013-02-02
  • 2021-09-29
  • 2022-01-27
相关资源
最近更新 更多