I have a basic class:
export default class Foo extends Component{
constructor(props){}
woop(){
somethingimportanthappening..
}
}
in the other component I import it like this:
import Foo from './Foo'
export default class Component2 extends Component{
constructor(props){}
randomfunction(){
Foo.woop() // FAILS
}
}
How can I call the function "woop" from the other component (Component2)? Foo.woop() isn't working ..
Imo, the proper way to call a function of a different class to pass the function callback as props (if there is a parental relation). If there isn't any, triggering Events using react-native-simple-events is fairly simple. Alternatively, you can use Redux which makes your app more robust.
The short answer is to use ViewChild to call the function on component B.
In React a component have an independent function, so in Foo component you define it, something like
export default class Foo extends Component{
constructor(props){}
woop(){
somethingimportanthappening..
}
render() {
<div>Class Foo</div>
}
}
and when you want to use Foo component, you just import and use
<Foo />
and if you want to use a function in Foo component, you can define a reference to Foo
<Foo ref="foo" />
then use it by
import Foo from './Foo'
export default class Component2 extends Component{
constructor(props){}
randomfunction(){
this.refs.foo.woop();
}
render() {
return <Foo ref="foo" />
}
}
Since woop
is not a static
function you cannot Foo.woop()
You should instantiate a Foo
instance as follows:
import Foo from './Foo'
export default class Component2 extends Component{
private fooInstance: Foo;
constructor(props){
this.fooInstance = new Foo(props);
}
useFoo(){
this.fooInstance.woop();
}
}
Let me know if something is unclear :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With