【问题标题】:How to check if Dom Element or React Component如何检查 Dom 元素或 React 组件
【发布时间】:2021-10-21 17:13:51
【问题描述】:

在创建 HOC 时,我不确定要包装哪种组件,有时它是另一个 React 组件,有时它可能是一个普通的 DOM 元素,如 lia

WrappedComp = myHOC(BaseComponent)

MyHOC 会将额外的 props 传递给被包装的组件,并且在大多数情况下,这将正常工作。

但有时当 BaseComponent 是 li 时,它不会接受额外的 props,React 会抛出警告 Unkown Prop Warning 说 DOM 元素不接受非标准 dom 属性:https://facebook.github.io/react/warnings/unknown-prop.html

那么我如何检查 BaseComponent 是否是 DOM 元素? 如果是这样,我不会将额外的道具传递给它。

有没有更好的方法来做到这一点?

【问题讨论】:

  • 你检查console.log(BaseComponent)的输出了吗?
  • 为什么需要将 HOC 包裹在每个组件上?是否可以包装和导出要使用它扩展的组件?
  • 最简单的检查是看它是否为function,typeof(BaseComponent) == "function",对于HTML组件,react 使用string
  • 这个检查本身并不能解决问题,因为 React 会在任何定义了 propTypes 的组件上给你这些警告。

标签: javascript reactjs dom


【解决方案1】:

检查BaseComponent 是否为 React 组件,并添加所需的 props。

if(BaseComponent.prototype.isReactComponent){
    //add props
}

【讨论】:

  • 有关于这个的文档吗?
  • github.com/facebook/react/blob/…可以在源码中看到。
  • 我猜不应该使用未记录的内部函数,因为它们可能随时更改。如果使用纯渲染函数,这也行不通
【解决方案2】:

简答:
检查元素是否为 string 类型以检查元素是否为 DOM 元素。
检查元素是否为 function 类型以检查元素是否为 React 组件。

示例:

  if (typeof BaseComponent.type === 'string') {
    return BaseComponent
  }
  // add props

长答案:
正如the React documentation 中定义的那样,像<li><span> 这样的内置组件会导致将字符串'li''span' 传递给React.createElement,例如React.createElement("li").
<Foo /> 之类的大写字母开头的类型编译为React.createElement(Foo),并对应于您的 JavaScript 文件中定义或导入的组件。

因此,React 组件的类型为 function,而 DOM 组件的类型为 string

以下WrapperComponent 记录每个子元素的typeof child.type。输出为functionstringstring

function WrappedComponent({children}) {
  return React.Children.map(children, child => {
    console.log(typeof child.type)
    ...
  })
}

const BaseComponent = ({children}) => children

function App() {
  return (
    <WrappedComponent>
      <BaseComponent>This element has type of function?</BaseComponent>
      <span>This element has type of string</span>
      <li>This element has type of string</li>
    </WrappedComponent>
  )
}

【讨论】:

  • 我相信这是正确的答案
猜你喜欢
  • 2016-01-16
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 1970-01-01
  • 2014-09-30
  • 2014-11-14
相关资源
最近更新 更多