【问题标题】:How to avoid the error "Unknown prop <> on tag. Remove this prop from the element"?如何避免错误“Unknown prop <> on tag. Remove this prop from the element”?
【发布时间】:2017-09-13 17:28:59
【问题描述】:

请问,我该如何以另一种方式重写此代码以避免出现以下错误?

     render() {
            const { children, ...props } = this.props;
            return <div {...props} ref={this.setRef}>{children}</div>
      }

我收到此错误:

标签上的未知道具onClickOutside。从元素中移除这个道具。详情(https://facebook.github.io/react/docs/higher-order-components.html#static-methods-must-be-copied-over

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

Native DOM 元素只允许具有 Native DOM 属性。你不能传递任何你想要的属性(prop)。
如果您知道此元素需要哪些有效道具,则可以将它们从道具中销毁并显式传递。
例如:

 render() {
            const { children, onClickOutside } = this.props;
            return <div onClick={onClickOutside} ref={this.setRef}>{children}</div>
      }

【讨论】:

    【解决方案2】:

    您可以简单地从您转移的...props 中删除:

    render() {
                const { children, onClickOutside, ...props } = this.props;
                return <div {...props} ref={this.setRef}>{children}</div>
          }
    

    如果您希望 onClickOutside 映射到 divonClick,则显式处理:

    render() {
                const { children, onClickOutside, ...props } = this.props;
                return <div {...props} onClick={onClickOutside} ref={this.setRef}>{children}</div>
          }
    

    任何版本的 React

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      • 2020-09-11
      • 2020-08-27
      • 2022-11-20
      • 2017-07-25
      • 1970-01-01
      • 2019-09-24
      相关资源
      最近更新 更多