![](/img/trans.png)
[英]How to properly use React.StatelessFunctionalComponent<Props> on a stateless functional component?
[英]React - how to determine if component is stateless/functional?
我有功能/无状态组件和继承自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 hooks 的引入,函数式组件不再被称为无状态的,因为它们也可以是有状态的。
从 React 0.14 开始, React.Component
就存在isReactComponent
特殊属性。 这允许确定组件是否是类组件。
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
类型。
这现在对我有用(React 16.12.0)来测试一个组件是否是一个函数。 (我需要它来处理是否需要使用React.forwardRef
包装组件以避免出现https://github.com/yjose/reactjs-popup/issues/137 之类的问题)
(typeof component === "object" && typeof component.type === "function")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.