简体   繁体   中英

How can I call a method from an other class/component in javascript?

I am still a rookie in frontend. I have 2 NON RELATED (no parent/child relation) classes:

search.js
Class Search{
   method,
   state
}

view.js
Class view{
     content
}

I am trying to:

  • call a search.js method from view.js .
  • change state value of search.js from view.js

Additional info:

  • I have already tried using helper functions . It was not the desired solution.
  • I am using Preact which is a leightweight version of React.

Thanks!

Code:

export default class Search extends Component {
    constructor() {
        this.state = {
            input: ""
        };
    }

    search(input) {
        this.setState({ input: input });
    }
}

If the classes are unrelated, then there are only three ways you can use a class's methods outside the class (or, really, inside it):

  1. If it's a static method, call it directly:

     Search.theStaticMethod()
  2. If it's a prototype or instance method, the usual thing is to create an instance and then call the method on that instance:

     const s = new Search(/*...*/); s.prototypeOrInstanceMethod();
  3. If it's a prototype method, you can call it without creating an instance, but it's extremely likely to be incorrect to do so:

     // ALMOST CERTAINLY NOT THE RIGHT THING Search.prototype.prototypeMethod();

    There's a variation on that where you apply the method to an object, even though that object wasn't created via new Search :

     // ALMOST CERTAINLY NOT THE RIGHT THING const obj = {}; Search.prototype.prototypeMethod.call(obj);

    The method will get the object as this , and may or may not work correctly depending on how it's written.

You need an instance of class as answered already.

const myInstance = new Search();

You can export this instance instead of exporting class.

export {myInstance};

In view.js you need to import it

import {myInstance} from './relative-path';

And then you call method

myInstance.search('someInput');

Taking more react than vanilla js ... probably already answered here or even (primitively) here

I have 2 NON RELATED (no parent/child relation) classes:

Both in the same screen/view/app/component tree? Then indirectly but still related.

I am trying to:

  • call a search.js method from view.js.
  • change state value of search.js from view.js

There are a few ways to manage common state (values or methods):

  • state in common parent ( lifting state up ), even top <App /> component
  • using refs
  • using context api
  • redux
  • apollo client

Using Preact - then search for some tiny global state management, fe statext or unstated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM