Reputation: 1137
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.
Upvotes: 1
Views: 32
Reputation: 61
I think the value you want is 'myItem.label', so to make your example work, you'd write:
const myItem: Props = {
label: "AwesomeName",
style: myStyles.ordinaryItem,
action: function() {
someResolver.resolveSomething(myItem.label);
}
Upvotes: 1
Reputation: 361
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
interface Props {
label?: string;
url?: string;
style?: string;
action?: (args: FuncArguments) => void;
[key: string]: any;
}
const someResolver = {
resolveSomething: (label: string) => {
console.log("The resolved label: ", label);
}
};
const myItem : Props {
label: "AwesomeName",
style: myStyles.ordinaryItem,
action: function () {
someResolver.resolveSomething(this.label);
}
};
https://www.w3schools.com/js/js_arrow_function.asp
Upvotes: 0