反应 PropTypes DOM 元素?

React PropTypes DOM element?

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

This pagePropTypes.element 实际上是一个 React 元素,那么 DOM[= 的等价物是什么19=]元素?

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

The Element interface represents an object of a Document. This interface describes methods and properties common to all kinds of elements. Specific behaviors are described in interfaces which inherit from Element but add additional functionality. For example, the HTMLElement interface is the base interface for HTML elements, while the SVGElement interface is the basis for all SVG elements.

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>

以列表组件为例:

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

适合我。

PropTypes.instanceOf(Element)

正在为我工​​作。您还可以添加 isRequired:

PropTypes.instanceOf(Element).isRequired

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

建议改用PropTypes.object