【问题标题】:React PropTypes DOM element?反应 PropTypes DOM 元素?
【发布时间】:2016-09-08 23:37:50
【问题描述】:

如何将属性标记为必须是 DOM 元素?

This page 表示PropTypes.element 实际上是一个 React 元素,那么 DOM 元素的等价物是什么?

【问题讨论】:

  • 你的意思是DOM元素的类型吗?可以使用针对 someNode.constructor.name 的自定义 prop 检查器来检查特定类型。
  • @MatthewHerbst 不,我的意思是 any DOM 元素。 divspaninput,随便。
  • React.PropTypes.node?
  • @vijayst 即使它们是使用document.getElementById 获取的或使用document.createElement 创建的,不是 React.createElement("input")?
  • @elmeister node 太松了。它包括数字、字符串和数组。

标签: reactjs react-proptypes


【解决方案1】:
PropTypes.instanceOf(Element)

为我工作。你也可以添加 isRequired:

PropTypes.instanceOf(Element).isRequired

【讨论】:

  • 有nodejs等价物吗?
  • 您现在可以使用PropTypes.elementType,如下所述:stackoverflow.com/questions/48007326/…
  • 扩展此答案以包括如何使用 div 与导入组件之间的区别可以让您获得一些额外的代表,只是说
  • 如果你对你的应用进行 SSR,你应该避免使用这个,因为 Element 在 nodejs 中将是 undefined。如果你从你的生产版本中去掉你的 PropTypes 你会很好。但即便如此,你还是会在开发构建中抛出错误。
【解决方案2】:

您可以检查传递的属性是否为Element的实例:

Element 接口表示 Document 的一个对象。该接口描述了所有类型元素共有的方法和属性。特定行为在从 Element 继承但添加额外功能的接口中描述。例如,HTMLElement 接口是 HTML 元素的基础接口,而 SVGElement 接口是所有 SVG 元素的基础。

class Some extends React.Component {
  render() {
    return (
      <div> Hello </div>
    );
  }
}

const validateDOMElem = (props, propName, componentName) => {
  if (props[propName] instanceof Element === false) {
    return new Error(
      'Invalid prop `' + propName + '` supplied to' +
      ' `' + componentName + '`. Validation failed.'
    );
  }
}

Some.propTypes = {
  htmlElem: validateDOMElem,
};

const para = document.getElementById('para');

ReactDOM.render(<Some htmlElem={para} />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>

<div id="app"></div>
<p id="para"></p>

【讨论】:

  • 也可以不创建自定义验证器而使用PropTypes.instanceOf(Element)
【解决方案3】:

以列表组件为例:

MyList.propTypes = {
  children: PropTypes.instanceOf(<li></li>),
}

为我工作。

【讨论】:

  • 我收到警告Failed prop type: Right-hand side of 'instanceof' is not callable 如果我使用它,这在 2019 年不再起作用了吗?
【解决方案4】:

PropTypes.instanceOf(Element) 不适用于服务器端渲染,因为ReferenceError: Element is not defined

建议改用PropTypes.object

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 2018-09-23
    • 2017-09-21
    • 2022-07-21
    • 2019-12-14
    • 2014-11-14
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    相关资源
    最近更新 更多