最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I callexecute a function from another component in react native? - Stack Overflow

programmeradmin1浏览0评论

How do I call other ponent function in my current ponent 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???
    }
}

How do I call other ponent function in my current ponent 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???
    }
}
Share asked Sep 29, 2015 at 14:29 phongyewtongphongyewtong 5,31915 gold badges59 silver badges87 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 1

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
    }
}

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.

Obviously, it is not a remended way in ReactJS, even React-Native. Maybe you wanna follow the object-oriented programming rules but here we have fully functional development in ReactJS. for such your case I prefer to use a helper function and in both of the classes, I import and use the helper function:

// set value helper function

export const setValueHelper = () => {
  // do something
};

Then in the classes:

import { setValueHelper } from 'helpers';

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

    constructor(props) {
        super(props);
    }

    setValue(){
      setValueHelper();
    }
}
import { setValueHelper } from 'helpers';

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

    constructor(props) {
        super(props);   
    }

    setValue(){
        setValueHelper();
    }
}
发布评论

评论列表(0)

  1. 暂无评论