React - 如何确定组件是否为无状态/功能?

问题描述 投票:13回答:3

我有从React.Component继承的功能/无状态组件和组件:

const Component1 = () => (<span>Hello</span>)

class Component2 extends React.Component {
  render() {
    return (<span>Hello</span>)
  }
}

如何确定组件是否为无状态?有官方的方法吗?

isStateless(Component1) // true
isStateless(Component2) // false
javascript reactjs
3个回答
15
投票

你可以查看它的原型,例如:

function isStateless(Component) {
    return !Component.prototype.render;
}

4
投票

类组件本质上是有状态的,但随着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代码库中执行类似的检查。

由于组件可以是各种事物,如上下文ProviderConsumerisFunctionalComponent(Component)可能不等于!isClassComponent(Component)


2
投票

取决于人们所谓的“无国籍”。如果无国籍者意味着“不能有一个ref”那么它是:

function isStateless(Component) {
  return typeof Component !== 'string' && !Component.prototype.render
}

更新:React组件还有一个新的PropTypes.elementType类型(不是“元素”)。

© www.soinside.com 2019 - 2024. All rights reserved.