I'm trying to log all the function class in React class component, search the web and ask everywhere and i got this
const listOfFunctionClass = Object.getOwnPropertyNames(MyClass.prototype)
It work! But problem is it only show the lifeCycle and function when i try to log console.log(listOfFunctionClass)
, do not include arrow function
Example
class Foo extends React.Component{
functionA(){} ==>will log
functionB = () =>{} ===> will not show on log
componentDidUpdate() ==> will log on log
}
It will have an array like [functionA, componentDidUpdate]
So how can i add arrow function on proptype?
CodePudding user response:
While you can technically add an arrow function onto the prototype by assigning to the .prototype
property outside:
class Foo extends React.Component {
}
Foo.prototype.fn = () => {
// ...
}
Due to how arrow functions work, you won't be able to access the this
of the instance inside it. Such an arrow function would only be useable if all the data it needed was passed to it.
But using a standard method would make more sense in most situations
class Foo extends React.Component {
fn() {
// ...
or a class field
class Foo extends React.Component {
fn = () => {
You can't easily detect what class fields are on a class, because they're syntax sugar for
class Foo extends React.Component {
constructor() {
this.fn = () => {
They're not on the prototype - they're only on instances. You'll have to examine the instance itself to see what properties it has in order to find such a class field.
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>
That said, this sort of dynamic analysis of what properties exist on an object is pretty weird. I can't think of when such an approach would be the best one.