Answer the question
In order to leave comments, you need to log in
How to get props in react static method?
I need to get props in a static property. Why can't I get props in a static method in the same way as in other methods?
My code:
class Field extends React.Component {
static ifFieldNotEmpty() {
const { fields } = this.props; // not works
console.log(this);
}
render() {
const { fields } = this.props; // work fine
return (
<h2>render component</h2>
);
}
}
Answer the question
In order to leave comments, you need to log in
Because static works on the class, not on the instance.
In a static method, this.props cannot be accessed because it refers to the instance.
In this example, you are doing a meaningless operation - in a static method, you work with the current context of the class instance (the context in this case is our this)
To solve the problem, you must either pass props as a parameter to the static method, or not work with the context, or work only with static class methods.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question