![](/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.