我正在嘗試記錄 React 類組件中的所有函式類,搜索網路并到處詢問,我得到了這個
const listOfFunctionClass = Object.getOwnPropertyNames(MyClass.prototype)
這行得通!但問題是它只在我嘗試登錄時顯示生命周期和功能console.log(listOfFunctionClass),不包括箭頭功能
例子
class Foo extends React.Component{
functionA(){} ==>will log
functionB = () =>{} ===> will not show on log
componentDidUpdate() ==> will log on log
}
它將有一個像[functionA, componentDidUpdate]
那么如何在 proptype 上添加箭頭功能?
uj5u.com熱心網友回復:
.prototype雖然您可以通過分配給外部屬性從技術上向原型添加箭頭功能:
class Foo extends React.Component {
}
Foo.prototype.fn = () => {
// ...
}
由于箭頭函式的作業方式,您將無法訪問其中this的實體。只有將所需的所有資料都傳遞給它時,這樣的箭頭函式才可用。
但是在大多數情況下使用標準方法會更有意義
class Foo extends React.Component {
fn() {
// ...
或類欄位
class Foo extends React.Component {
fn = () => {
您無法輕松檢測到類中的類欄位,因為它們是語法糖
class Foo extends React.Component {
constructor() {
this.fn = () => {
它們不在原型上——它們只在實體上。您必須檢查實體本身以查看它具有哪些屬性才能找到這樣的類欄位。
const builtinReactInstanceProperties = ['props', 'context', 'refs', 'updater'];
class Foo extends React.Component {
fn = () => {}
}
const instance = new Foo();
console.log(
Object.getOwnPropertyNames(instance)
.filter(propName => !builtinReactInstanceProperties.includes(propName))
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
也就是說,這種對物件上存在哪些屬性的動態分析非常奇怪。我想不出這種方法什么時候是最好的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/465298.html
標籤:javascript 反应 反应式
上一篇:為什么粘性標題卡住了?
