Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call/execute a function from another component in react native?

How do I call other component function in my current component in react native? They are both in different script as well.

Anyone know how to do this in react native?

//ClassOne.js
class ClassOne extends React.Component {

    constructor(props) {
        super(props);
    }

    setValue(){
    }
}

//ClassTwo.js
class ClassTwo extends React.Component {

    constructor(props) {
        super(props);   
    }

    callSetValue(){
        ClassOne.setValue(); HOW???
    }
}
like image 906
phongyewtong Avatar asked Oct 31 '22 18:10

phongyewtong


2 Answers

You can pass in ClassOne.setValue as a property to ClassTwo.

//ClassOne.js
class ClassOne extends React.Component {

    constructor(props) {
        super(props);
    }

    setValue(){
        // Do stuff
    }
}

//ClassTwo.js
class ClassTwo extends React.Component {

    constructor(props) {
        super(props);   
    }

    callSetValue(){
        if (this.props.onSetValue) this.props.onSetValue(); // this can be set to any function, including ClassOne's setValue
    }
}
like image 171
Fozzle Avatar answered Nov 02 '22 23:11

Fozzle


Unless the function you are wanting to call is static you must instantiate whatever class you want inside the scope of where you want to call the function. Say in ClassTwo you want to call a method in ClassOne... Instantiate an instance of ClassOne inside of ClassTwo and then call the function using that object.

like image 26
httpNick Avatar answered Nov 02 '22 23:11

httpNick