Reputation: 49
I'm having a hard time executing a class method outside of it and in a function
class Player extends Component {
constructor(props) {
super(props);
}
test(){
console.log('test')
}
}
export default Player;
what I tried to do:
function() {
Player.test();
}
class Player extends Component {
constructor(props) {
super(props);
}
test(){
console.log('test')
}
}
export default Player;
I tried several ways to run this method in the function but it didn't help.
Upvotes: 3
Views: 361
Reputation: 1285
Create Player class object in App class
var obj = new Player();
now access method with the help of obj
obj.test();
Upvotes: 0
Reputation: 374
My question is: do you need Player to be a Component? If you don't, just do:
function() {
new Player().test();
}
class Player {
test(){
console.log('test')
}
}
export default Player;
Upvotes: 0
Reputation: 829
you can try using static methods:
The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.
class ClassWithStaticMethod {
static staticMethod() {
return 'static method has been called.';
}
}
console.log(ClassWithStaticMethod.staticMethod());
// expected output: "static method has been called."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static
Upvotes: 0
Reputation: 1646
To do this, you have to include Player
inside the render
of the class which you want to execute it. Then, set a ref
to that Player
component and then call your function through the ref
.
Here is a working example...
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Constants from 'expo-constants';
class Player extends Component {
constructor(props) {
super(props);
}
test(){
console.log('test')
}
render() {
return(
null
)
}
}
export default class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.Player.test()
}
render() {
return(
<View>
<Text>Test</Text>
<Player ref={component => this.Player = component}/>
</View>
)
}
}
Upvotes: 2