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:
Additional info:
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):
If it's a static
method, call it directly:
Search.theStaticMethod()
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();
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):
<App />
componentUsing 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.