【问题标题】:Why do I get an Invariant Violation when I don't include an optional prop?当我不包含可选道具时,为什么会出现 Invariant Violation?
【发布时间】:2019-11-20 13:38:08
【问题描述】:

这与我在这里提出的前一个问题(How do I style a material-ui Icon which was passed as prop)有关。我最初的问题已解决(即,将 Icon 元素作为道具传递并在接收组件中对其进行样式设置)。

但是我希望该道具是可选的。当我没有通过它时,我会得到一个我无法弄清楚的 Invariant Violation。我尝试了许多选项来处理“未定义”道具,但无济于事。

有关问题,请参见此处。

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    那是因为你没有正确渲染你的 div,它必须由函数渲染

    const Div = () => <div />;
    
    function MyComponentWithIconProps(props) {
      const styles = useStyles();
      const StatusImage = props.statusImage ? props.statusImage : Div;
      return (
        <div>
          <StatusImage className={styles.iconStyle} />
        </div>
      );
    }
    

    https://codesandbox.io/s/add-class-to-icon-prop-nmpw8?fontsize=14&hidenavigation=1&theme=dark

    【讨论】:

    • 啊,我明白了。所以基本上从函数中返回它“包装”它作为一个变量。太好了,谢谢。
    【解决方案2】:

    想象一下,如果你的StatusImage 已经设置为&lt;div/&gt;,那么你又像&lt;StatusImage /&gt; 那样调用它,这没什么意义吧?

    改为这样做:

    function MyComponentWithIconProps(props) {
      const styles = useStyles();
      const statusImage = props.statusImage ? <props.statusImage className={styles.iconStyle}/> : <div />;
      return (
        <div>
          {statusImage}
        </div>
      );
    }
    

    【讨论】:

    • 啊,是的,我明白了。谢谢你的解释。
    【解决方案3】:

    您可以将默认值设置为StatusImage

    function MyComponentWithIconProps(props) {
      const styles = useStyles();
    
      const { statusImage: StatusImage = 'div' } = props;
      // OR
      // const MyDiv = (props) => <div {...props} />
      // const { statusImage: StatusImage = MyDiv } = props;
    
      return (
          <div>
            <StatusImage className={styles.iconStyle} />
          </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多