I’m using a primereact component, whose props include a function, and I want to use one of the other props in this function. The overall scheme of things looks like this:
interface Props {
label?: string;
url?: string;
style?: string;
action?: (a: FuncArguments): void;
[key: string]: any;
}
The thing I want to do is this:
const myItem : Props {
label: "AwesomeName",
style: myStyles.ordinaryItem,
action: () => {
someResolver.resolveSomething(this.label);
}
};
Well… this.label
is not accessible, because this
is somehow always undefined and cannot even be cast to Props
.
I’m not too much of a React wiz, or even a JS wiz, so this entire situation is making me a little confused.
3
Answers
The issue you’re facing is related to how
this
is scoped in JavaScript, especially within the context of arrow functions.Using Regular Function: When you use a regular function, you can bind this to it, ensuring it refers to the correct context. This is useful in class components where you need to access component properties and methods.
Passing Props Directly: If you’re defining the object outside of a class, you can directly reference the properties of myItem without worrying about the this context.
Check this.
You are using arrow function, using this in an arrow function only provide you properties within the scope of the arrow function. You can either pass a label to the function or use a regular function
https://www.w3schools.com/js/js_arrow_function.asp
I think the value you want is ‘myItem.label’, so to make your example work, you’d write: