我有从React.Component
继承的功能/无状态组件和组件:
const Component1 = () => (<span>Hello</span>)
class Component2 extends React.Component {
render() {
return (<span>Hello</span>)
}
}
如何确定组件是否为无状态?有官方的方法吗?
isStateless(Component1) // true
isStateless(Component2) // false
你可以查看它的原型,例如:
function isStateless(Component) {
return !Component.prototype.render;
}
类组件本质上是有状态的,但随着React钩子的引入,功能组件不再被称为无状态,因为它们也可以是有状态的。
自React 0.14起,isReactComponent
特殊财产存在于React.Component
。这允许确定组件是否是类组件。
function isFunctionalComponent(Component) {
return (
typeof Component === 'function' // can be various things
&& !(
Component.prototype // native arrows don't have prototypes
&& Component.prototype.isReactComponent // special property
)
);
}
function isClassComponent(Component) {
return !!(
typeof Component === 'function'
&& Component.prototype
&& Component.prototype.isReactComponent
);
}
在React代码库中执行类似的检查。
由于组件可以是各种事物,如上下文Provider
或Consumer
,isFunctionalComponent(Component)
可能不等于!isClassComponent(Component)
。
取决于人们所谓的“无国籍”。如果无国籍者意味着“不能有一个ref
”那么它是:
function isStateless(Component) {
return typeof Component !== 'string' && !Component.prototype.render
}
更新:React组件还有一个新的PropTypes.elementType
类型(不是“元素”)。