如何将属性标记为必须是DOM元素?
这个页面说PropTypes.element
实际上是一个 React 元素,那么对应的DOM元素是什么呢?
PropTypes.instanceOf(Element)
对我来说有效。您还可以添加isRequired:
PropTypes.instanceOf(Element).isRequired
PropTypes.elementType
,具体说明可以参考这里:https://dev59.com/0FYN5IYBdhLWcg3wEEnU#51127130 - PandaioloElement
会变成未定义的。如果你从生产构建中剥离你的PropTypes,那么在此方面就没问题了。但即使如此,在开发构建中仍然会抛出一个错误。 - Carl von BuelowPropTypes.elementType
不适用于原生 DOM 元素实例。请参见此处:https://github.com/facebook/prop-types/issues/334 和此处:https://github.com/facebook/prop-types/pull/211。 - sydd您可以检查传递的属性是否是Element
的实例:
Element
接口表示文档的对象。该接口描述了所有类型元素的公共方法和属性。特定行为在继承自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)
。 - Michael RadionovMyList.propTypes = {
children: PropTypes.instanceOf(<li></li>),
}
这对我来说没问题。
Failed prop type: Right-hand side of 'instanceof' is not callable
。 这意味着在2019年以后不再起作用了吗?请帮我翻译一下。 - micnilPropTypes.instanceOf(Element)
在服务器端渲染时不起作用,因为会出现ReferenceError: Element is not defined
建议改用PropTypes.object
someNode.constructor.name
进行。 - Matthew Herbstdiv
,span
,input
,无论什么。 - mpenReact.PropTypes.node
? - elmeisterdocument.getElementById
获取的,或者是通过document.createElement
创建的,并且不是通过React.createElement("input")
创建的? - mpennode
的范围太宽泛了,它包含数字、字符串和数组。 - mpen